0
我正在嘗試Angular 2中的一個場景,在這裏我們可以從下拉列表中選擇Super Powers,這些下拉列表將從預定義列表中填充。而且,我不希望任何兩個超級英雄擁有相同的超級動力。在Angular中過濾出選項值
我已經嘗試過,如下所示。
HTML:
<div class="form-group">
<label>Hero One</label>
<select (ngModelChange)="onChange($event)" class="form-control" name="sel">
<option *ngFor="let pow of powers">
<span *ngIf="check(pow)">{{pow}}</span>
</option>
</select>
</div>
<div class="form-group">
<label>Hero Two</label>
<select (ngModelChange)="onChange($event)" class="form-control" name="sel1">
<option *ngFor="let pow of powers">
<span *ngIf="check(pow)">{{pow}}</span>
</option>
</select>
</div>
<div class="form-group">
<label>Hero Three</label>
<select (ngModelChange)="onChange($event)" class="form-control" name="sel2">
<option *ngFor="let pow of powers">
<span *ngIf="check(pow)">{{pow}}</span>
</option>
</select>
</div>
Component.ts
export class HeroFormComponent {
powers = ['Really Smart', 'Super Flexible', 'Super Hot', 'Weather Changer'];
array = [];//storing the previously selected superpowers
check(p) {
var condition = this.array.length;
for (var i = 0; i <= this.array.length; i++) {
if (condition != 0) { //dont check if array is empty, just return true
if (p === this.array[i]) { //return false if the superpower is present
return false;
}
//return true, since power doesnt belong to anyother hero
return true;
}
return true;
}
}
onChange(p: string) {
this.array.push(p);//push the selected values in this array;
console.log(this.array);
}
}
我想我沒有使用ngFor或ngIf得當,可以請你指出我在做什麼錯了,還是我怎麼會做到這一點。