Search code examples
angulartypescriptangular-formsangular-template

Angular string interpolation prints empty string on JSON object value


In my typescript class:

user = {
    username: '',
    email: '',
    secret: '',
    gender: '',
    answer: '',
};

i have a button called onSubmit:

onSubmit() {
    this.submitted = true;
    console.log(this.form);
    this.user.username = this.form.value.userData.username;
    console.log(this.user.username);
}

and in my HTML:

<div class="row" *ngIf="submitted">
    <div class="col-xs-12">
        <h3>Your Data</h3>
        <p>Username: {{ user.username }}</p>
    </div>
</div>

The console log clearly prints the value of the user.username and I can see it in the console. But the html just shows:

Your Data

Username:


Solution

  • According to your code https://pastebin.com/1nSHRCPb

    The issue had happened because of line 18

        ...
        #user="ngModel">
    

    You've created a template variable user. That's why you get nothing when called user.username in your template.