2

I have a simple input that I want to reset the value to empty string after I am adding hero. The problem is the value is not updated. why?

@Component({
  selector: 'my-app',
  template: `
      <input type="text" [value]="name" #heroname />
      <button (click)="addHero(heroname.value)">Add Hero!</button> 

      <ul>
        <li *ngFor="let hero of heroes">          
          {{ hero.name }}        
        </li>
      </ul>
  `,
})
export class App {
  name: string = '';
  heroes = [];

  addHero(name: string) {
   this.heroes.push({name});
   // After this code runs I expected the input to be empty
   this.name = '';
  } 

}
1
  • Why push({name}), and not just push(name), push({name: name})? Commented Dec 19, 2016 at 9:31

2 Answers 2

3

You have one-way binding so when you're typing something in your input your name property isn't changed. It remains "". After clicking on Add hero! button you doesn't change it.

 addHero(name: string) {
   this.heroes.push({name}); // this.name at this line equals ''
   this.name = ''; // it doesn't do any effect
 } 

Angular2 will update value property only if it is changed.

enter image description here

Use two-way binding which is provided by @angular/forms

[(ngModel)]="name" 

to ensure that your name property will be changed after typing.

Another way is manually implementing changing

[value]="name" (change)="name = $event.target.value"
Sign up to request clarification or add additional context in comments.

5 Comments

But I'm changing it in the addHero function. this.name = '';
I'm sorry I'm not understand the comment.
If the [value] property is bound to the name in my component, when I changing the name I expect the value to be change also.
Are you saying you want this to output nothing {{ hero.name }} ?? or are you saying you want that to say the hero name but nothing to show in the input field?
Can u share please how u get to this code when debugging? (the code in your image)
0

In Angular Template binding works with properties and events, not attributes. as per html attribute vs dom property documentation of angular so as you have used [value] binding its binding to attributes not to the property of that input and because of it value remain in it after you set this.name = "".

2 Comments

It's property binding
From the article that ranakrunal9 mentions: Attributes initialize DOM properties and then they are done. Property values can change; attribute values can't.

Your Answer

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