1

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:

9
  • To edit: the onSubmit is somewhere in my HTML and it works fine because i can see the console output. Commented Feb 20, 2019 at 20:52
  • What is the changeDetection strategy on the component? Commented Feb 20, 2019 at 20:52
  • @OneLunchMan Can you elaborate on the question? Commented Feb 20, 2019 at 20:54
  • @OneLunchMan pastebin.com/1nSHRCPb that is the HTML code Commented Feb 20, 2019 at 20:55
  • The typescript is what I am looking for. Also, read up on this blog.angular-university.io/… Commented Feb 20, 2019 at 20:56

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this solves the issue. This was really nasty to spot. What made it worse was that I was following along with the tutorial.
You've just looked through tired eyes. That happens. Glad, that I could help.
1

The prior reply will solve your issue. I did a stackblitz of it here: https://stackblitz.com/edit/angular-hirffj

But you may be able to simplify your code even further if you use two-way binding.

        <input
         type="text" 
         id="username" 
         class="form-control"
         [(ngModel)]="user.username"
         name="username"
         required>

Then your input element and your user.username property will stay in sync.

Also note that the setValue and patchValue shown in your component code is for reactive forms, not template driven forms. Since you are using template driven forms, if you change to use two-way binding you can set the values into the form just using the object properties:

  suggestUserName() {
    this.user.username = 'Superuser';
  }

2 Comments

Thank you for the tip, much appreciated!
I have a more complete example using two-way binding here: stackblitz.com/edit/angular-template-forms-deborahk Hope it is helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.