簡體   English   中英

Angular 6如何將選中的復選框傳遞給ngModel

[英]Angular 6 how to pass selected checkbox to ngModel

我有選擇復選框(已迭代)到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,但仍然有顯示選中復選框的問題。 我怎樣才能做到這一點?

使用[(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>

演示

我建議你在模型中添加一個屬性並將其綁定在模板中。

<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 
  },  
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM