首页 文章

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

提问于
浏览
1

我的问题是这样的:

我有这个数组和变量:

// 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帖子以及其他一些内容,但没有找到看起来像我的情况的东西,也没有寻找答案的线索 . 据我了解双向数据绑定,当我单击复选框时,它将my selectedItem.main 的值更改为false . 但随后调用 setMain 并将其设置为true . 为什么复选框不会被检查?

任何实现这一目标的方法都很棒:) .

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

2 回答

  • 2

    Solution to your situation

    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

    有关详细信息,请查看: Angular 2 - Checkbox not kept in sync

  • 0

    我试过如下,请检查是否需要?

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

相关问题