Angular 6如何将选中的复选框传递给ngModel

问题描述 投票:2回答:2

我有选择复选框(已迭代)到ngModel的问题。

    <label class="btn btn-outline-secondary" 
     *ngFor="let test of tests"  >
      <input type="checkbox">
    </label>

在ts我有模型:

     testData = <any>{};

this.tests = [{
    id: 1, name: 'test1' 
  },
  {
    id: 2, name: 'test2' 
  },
  {
    id: 3, name: 'test3' 
  },  
]

我尝试使用ngModel和ngModelChange,但仍然有显示选中复选框的问题。我怎样才能做到这一点?

angular checkbox ngfor angular2-ngmodel
2个回答
3
投票

使用[(ngModel)]="test.name"

 <label class="btn btn-outline-secondary" *ngFor="let test of tests"  >
  <input type="checkbox" [(ngModel)]="test.selected" > {{test.name}} - {{test.selected}}
</label>

Demo


2
投票

我建议你在模型中添加一个属性并将其绑定在模板中。

<label class="btn btn-outline-secondary" *ngFor="let test of tests"  >
    <input type="checkbox" [(ngModel)]="test.isChecked">
</label>
this.tests = [{
    id: 1, name: 'test1', isChecked: false
  },
  {
    id: 2, name: 'test2', isChecked: true
  },
  {
    id: 3, name: 'test3', isChecked: false 
  },  
]
© www.soinside.com 2019 - 2024. All rights reserved.