我可能发现也可能没有发现 Angular 2 中的错误。基本上我想做的是创建一个从选择框中选择的选项的选定项目列表,当选择一个项目时,它会创建一个新的空选择框位于前一个框下方,以便用户可以连续添加所选项目。
所以我想要做的是将底部选择框重置回空值,但是当我尝试将 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
另一个奇怪的事情是,如果我将entity.selected设置为“蓝色”而不是0,那么它会将最后一个选择框默认为蓝色,但仅限于第一个选择。此后的任何选择都与前一个选择相同。
最佳答案
将 2 路数据绑定(bind) ([(ngModel)]
) 与 (change)
事件结合使用是非常糟糕的主意,因为您无法预测/Angular 无法控制将执行什么操作先处理。因此,您必须重写 entitySelect
函数以手动为 entity\a
分配值。第二点有完全相同的原因...对我有用的示例:
@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;
}
}
关于选择框的 Angular 2 ngModel 更改未更新所选选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41172446/