我正在Angular 2中尝试一个场景,我们可以在下拉列表中为英雄选择超级大国,这将从预定义的列表中填充。并且,我不希望任何两个超级英雄拥有相同的超级大国。
我试过如下。
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,请你指出我做错了什么,或者我怎么做。
答案 0 :(得分:1)
就我而言,我会做的是这样的事情:
<select (change)="updatePowers(power, hero1)" [(ngModel)]="hero1.power">
<option *ngFor="let pow of powers">...</option>
</select>
在您的组件中:
powers = ['P1', 'P2', 'P3'];
hero1 = { name: 'Harold', power: undefined };
updatePowers(power: string, hero: any): void {
if(hero.power) { this.powers.push(power); }
hero.power = power;
this.powers.slice(this.powers.indexOf(power), 1);
}
基本上,你所做的就是每当你改变力量时,它就会从阵列中退出,并被推入英雄。并且,如果你改变了英雄的力量,那么权力会被重新放入阵列,然后就会改变。
由于你有几个英雄,你可以做的是:
<ng-container *ngFor="let hero of heroes; let i = index">
<h1>{{hero.name}}'s power </h1>
<select (change)="updatePowers(power, hero)" [(ngModel)]="heroes[i].power">
<option *ngFor="let pow of powers">...</option>
</select>
</ng-container>
在您的组件中:
powers = ['P1', 'P2', 'P3'];
heroes = [
{ name: 'Harold', power: undefined },
{ name: 'Kumar', power: undefined },
];
updatePowers(power: string, hero: any): void {
if(hero.power) { this.powers.push(power); }
hero.power = power;
this.powers.slice(this.powers.indexOf(power), 1);
}