【问题标题】:two-way data binding of input checkbox element输入复选框元素的双向数据绑定
【发布时间】: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


【解决方案1】:

我已尝试如下,请检查您是否需要?

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

【讨论】:

  • hmm 尝试使用您的代码,但它的行为与我的相同......愿意为我提供一个工作的 plunker 吗?
【解决方案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

【讨论】:

  • 至少我有过人生第一次使用plunker的经验^.^
  • @Dzak,还有很长的路要走,:),快乐编码。
猜你喜欢
  • 2015-08-30
  • 2017-03-06
  • 1970-01-01
  • 2016-02-11
  • 2018-08-13
  • 1970-01-01
  • 2012-03-11
  • 1970-01-01
相关资源
最近更新 更多