【发布时间】:2018-08-03 07:32:06
【问题描述】:
我的问题是这样的:
我有这个数组和变量:
// the options
public items = [{id: 1, main: true}, {id: 2, main: false}, {id: 3, main: false}];
// the selected option
public selectedItem = this.items[0];
我的 html 看起来像这样:
<select id="itemOptions"
name="itemOptions"
[(ngModel)]="selectedItem">
<option *ngFor="let item of items" [ngValue]="item">{{item.id}}</option>
</select>
<input id="mainItem"
name="mainItem"
type="checkbox"
[(ngModel)]="selectedItem.main"
(ngModelChange)="setMain()" >
setMain 函数如下所示:
setMain() {
for(let item of this.items){
//set all items` main to false if they are not the selected item
if(this.selectedItem.id != item.id){
item.main = false;
}
//if it is the selected item, set it as the main item
else if(this.selectedItem.id == item.id){
item.main = true;
}
}
}
这里的重点是必须始终有一个主要项目。
但是当我选择主要项目并取消选中它时,该功能运行良好,main 保持true,但复选框仍未选中。
我已经阅读了this 的帖子以及更多内容,但没有找到与我的案例相似的内容,也没有找到答案的线索。
据我了解双向数据绑定,当我单击复选框时,它会将 selectedItem.main 的值更改为 false。但随后调用setMain 并将其设置回true。为什么复选框没有被选中?
实现这一点的任何方式都会很棒:)。
注意:我不想手动将复选框 checked 设置为 true。我想了解为什么双向数据绑定不能处理这种情况。
【问题讨论】:
-
使用检查事件代替
(ngModelChange)="setMain()" -
@SandipPatel 也试过这个。没用
-
你能提供plunker吗
-
@SandipPatel this 是我的第一个 plunker,所以我希望我做得很好 :)
标签: html angular typescript angular2-ngmodel