Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 复位后角度2输入值未更新_Javascript_Angular - Fatal编程技术网

Javascript 复位后角度2输入值未更新

Javascript 复位后角度2输入值未更新,javascript,angular,Javascript,Angular,我有一个简单的输入,我想在添加hero后将值重置为空字符串。问题是该值未更新。为什么? @Component({ selector: 'my-app', template: ` <input type="text" [value]="name" #heroname /> <button (click)="addHero(heroname.value)">Add Hero!</button> <ul>

我有一个简单的输入,我想在添加hero后将值重置为空字符串。问题是该值未更新。为什么?

@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 = '';
  } 

}
@组件({
选择器:“我的应用程序”,
模板:`
添加英雄!
    {{hero.name}
`, }) 导出类应用程序{ 名称:字符串=“”; 英雄=[]; addHero(名称:string){ this.heros.push({name}); //在这段代码运行之后,我希望输入是空的 this.name=''; } }
您具有单向绑定,因此当您在输入中键入内容时,
名称
属性不会更改。它仍然是
。点击
后添加英雄按钮,您不会更改它

 addHero(name: string) {
   this.heroes.push({name}); // this.name at this line equals ''
   this.name = ''; // it doesn't do any effect
 } 
Angular2仅在属性发生更改时才会更新
属性

使用由
@angular/forms

[(ngModel)]="name" 
确保键入后将更改您的
名称
属性

另一种方法是手动实现更改

[value]="name" (change)="name = $event.target.value"

在Angular
中,模板绑定使用属性和事件,而不是属性。
根据Angular,因为您使用了
[value]
将其绑定绑定到该输入的
属性,而不是该输入的
属性,因此在设置
this.name=“”后,值仍保留在其中

但我正在addHero函数中更改它。this.name='';很抱歉,我不理解注释。如果[value]属性绑定到我的组件中的名称,当我更改名称时,我希望该值也会更改。您是说希望它不输出任何内容{{hero.name}??或者你是说你想说英雄的名字,但没有显示在输入字段?你能分享一下你如何得到这段代码时,调试?(图像中的代码)ranakrunal9提到的文章中的属性绑定:
属性初始化DOM属性,然后完成。属性值可以更改;属性值不能使用。
为什么要按({name}),而不仅仅是按(name),按({name:name})?