2016-12-15 13 views
2

角度2のバグが見つかったかどうかわかりませんでした。基本的には、選択ボックスから選択したオプションの選択リストのリストを作成し、項目が選択されると、前の項目の下に新しい空の選択ボックスが作成され、ユーザーは選択した項目を継続的に追加できます。角度2 ngModelの選択ボックスの変更が更新されない

ボトムセレクトボックスを空の値に戻したいのですが、ngModelの値を0(または空)に戻すと、以前に選択したオプションでボトムセレクトボックスが保持されます。

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div *ngFor="let a of arr"> 
     <div *ngFor="let b of a.entities;let i = index"> 
      <select class="form-control input-sm" [(ngModel)]="a.entities[i]"> 
       <option *ngFor="let c of items" value="{{c}}">{{c}}</option> 
      </select> 
     </div> 
     <select class="form-control input-sm mb5" (change)="entitySelect(a)" [(ngModel)]="a.selected"> 
      <option value="0">- Select -</option> 
      <option *ngFor="let c of items" value="{{c}}">{{c}}</option> 
     </select> 
    </div> 
    `, 
}) 
export class App { 
    items:Array<string> = ['red','green','blue']; 
    constructor() { 
     this.arr = [{ 
      entities: [], 
      selected: 0 
     }] 
    } 
    entitySelect(entity) { 
     entity.entities.push(entity.selected); 
     entity.selected = 0; // Revert bottom select box back to empty 
    } 
} 

https://plnkr.co/edit/PMzbgEtyd4DFhObu1UVz

私が設定している場合、他の奇妙なことは、それが唯一の最初の選択で、青に最後の選択ボックスをデフォルト設定されます、「青」の代わりに、0と言ってentity.selectedされます。それ以降は、前の選択と同じままです。

https://plnkr.co/edit/Ze5uS1JjAmI7QXjQ17kQ

答えて

2

あなたが/角度はアクションが最初に処理されるかを制御することはできません予測することはできないよう(change)イベントに2ウェイデータバインディング([(ngModel)])を使用することは非常に悪い考えです。したがって、値entity\aを手動で割り当てるように、entitySelect関数を書き直す必要があります。 2番目の点はまったく同じ理由があります...私のために働く例:

@Component({ 
selector: 'my-app', 
template: ` 
    <div *ngFor="let a of arr"> 
     <div *ngFor="let b of a.entities;let i = index"> 
      <select class="form-control input-sm" [(ngModel)]="a.entities[i]"> 
       <option *ngFor="let c of items" value="{{c}}">{{c}}</option> 
      </select> 
     </div> 
     <select class="form-control input-sm mb5" (change)="entitySelect($event, a)" [ngModel]="a.selected"> 
      <option value="0">- Select -</option> 
      <option *ngFor="let c of items" value="{{c}}">{{c}}</option> 
     </select> 
    </div> 
`, 
}) 
export class App { 
    name:string; 
    items:Array<string> = ['red','green','blue']; 
    constructor() { 
     this.name = 'Angular2' 
     this.arr = [{ 
      entities: [], 
      selected: 0 
     }] 
    } 
    entitySelect($event, entity) { 
     entity.entities.push($event.target.value); 
     $event.target.value = 0; 
    } 
} 
+0

それは働いた。ありがとう! – Scot

関連する問題