2016-12-19 12 views
0

ヒーローを追加した後、空の文字列に値をリセットしたいという簡単な入力があります。問題は値が更新されていないことです。どうして?リセット後に角2の入力値が更新されない

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

} 
+0

プッシュ({name})、プッシュ(name)だけでなく、({name:name})をプッシュするのはなぜですか? – knobo

答えて

1

一方向バインディングを使用しているため、入力に何かを入力すると、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プロパティを更新します。

enter image description here

あなたnameプロパティが入力した後に変更されることを保証するために@angular/forms

[(ngModel)]="name" 

によって提供される双方向バインディングを使用。

もう一つの方法は、手動でそのではなく、入力のpropertyattributesに結合しているため、それ値の中に残る結合[value]を使用していたように、角度のhtml attribute vs dom property documentationごとに角度Template binding works with properties and events, not attributes.

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

しかしaddHero関数でそれを変更しています。 this.name = ''; –

+0

申し訳ありませんが、私はコメントを理解していません。 –

+0

[値]プロパティがコンポーネントの名前にバインドされている場合、名前を変更すると値も変更されると予想されます。 –

0

を変更し実施していますそれはthis.name = ""を設定した後です。

+0

プロパティバインディング – yurzui

+0

http://take.ms/5mV08 – yurzui

+0

ranakrunal9の記事では、「属性はDOMプロパティを初期化してから完了します。プロパティ値は変更可能です。属性値はできません。 – Joe

関連する問題