输入复选框元素的双向数据绑定

two-way data binding of input checkbox element

我的问题是这样的:

我有这个数组和变量:

// 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;
    }
  }
}

这里的重点是必须始终有一个主要项目。 但是当我 select 主要项目并取消选中它时,该功能运行良好并且 main 保持 true,但复选框仍未选中。

我已经阅读了 post 和更多内容,但没有找到与我的情况相似的内容,也没有找到答案的线索。 据我了解双向数据绑定,当我单击复选框时,它将 selectedItem.main 的值更改为 false。但随后调用 setMain 并将其设置回 true。为什么复选框没有被选中?

任何实现此目的的方法都很棒 :)。

注意:我不想手动将复选框 checked 设置为 true。我想了解为什么双向数据绑定无法处理这种情况。

解决你的情况

是把setMain的所有代码都放在setTimeout里面:

setMain() {
    setTimeout(() => {
        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;
            }
        }
    })
}

WORKING DEMO

更多详情请查看:

我试过如下,请检查是否符合您的要求?

<input id="mainItem" 
name="mainItem" 
type="checkbox"
[(ngModel)]="selectedItem.main"
(click)="setMain($event.target.value)" >

setMain(value) {  
    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 = !value;
        }
    }
}