我有一个简单的输入,我想在添加英雄后将值重置为空字符串。问题是该值没有更新。为什么?
@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 = '';
}
}
最佳答案
您有单向绑定(bind),因此当您在输入中键入内容时,您的 name
属性没有改变。它仍然是""
。点击Add hero!
后按钮,您无需更改它。
addHero(name: string) {
this.heroes.push({name}); // this.name at this line equals ''
this.name = ''; // it doesn't do any effect
}
Angular2 将更新 value
仅当属性发生更改时。
使用 @angular/forms
提供的双向绑定(bind)
[(ngModel)]="name"
确保您的name
属性将在输入后更改。
另一种方法是手动实现更改
[value]="name" (change)="name = $event.target.value"
关于javascript - Angular 2 输入值重置后未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41219146/