I am trying a scenario in Angular 2, where we can select Super Powers for the Heroes in a dropdown which will be populated from a predefined list. And, I dont want any two superheros to have the same Super Power.
I have tried like below.
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);
}
}
I guess I am not using the ngFor or ngIf properly, can you please point out what I am doing wrong, or how I could do it.