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

时间:2018-02-23 09:14:08

标签: html angular typescript angular2-ngmodel

我的问题是这样的:

我有这个数组和变量:

// 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 个答案:

答案 0 :(得分:2)

解决您的情况

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

答案 1 :(得分: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;
        }
    }
}
相关问题