默认选中的复选框需要取消选中角度6

时间:2019-03-14 13:00:56

标签: angular typescript

在此处输入我的组件代码,我将所有ID并绑定到已选中的复选框

for (var i = 0; i < this.featureData.length; i++) {
    var user = this.featureData[i]
    this.feature_id = user.feature_id;
    this.datauser.push(this.feature_id);
}

在这里我的HTML代码将数据绑定到复选框以选中

<div *ngIf="!!datauser?.length">
    <div class="ui test toggle checkbox">
        <input type="checkbox"  *ngFor="let data of datauser" [checked]="data == feature.feature_id"  (change)="addInSelectedFeatures(feature.Feature.feature_id)" [value]="feature.feature_id">
        <label></label>
    </div>
</div>
<div class="ui test toggle checkbox" *ngIf="!(!!datauser?.length)">
    <input type="checkbox"  name="" (change)="addInSelectedFeatures(feature.Feature.feature_id)" [value]="feature.feature_id">
    <label></label>
</div>

1 个答案:

答案 0 :(得分:0)

在html属性中选中定义复选框的初始值。更改此属性不会更改复选框视图。

在您的情况下,最好使用[[ngModel)]:

...
<input type="checkbox"
       *ngFor="let data of datauser"
       [checked]="data.id== feature.feature_id"
       [(ngModel)]="data.isChecked"
       (change)="onCheckboxValueChange(data, feature)">
...


简单的示例:
app.component.ts

import { Component } from '@angular/core';
import { routerAnimation } from '../shared/index';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {

  onCheckboxValueChange(data){
    console.log(data);
  }

}

app.component.html

<input type="checkbox"
       *ngFor="let data of [{id: 1, isChecked: true }, {id: 2,isChecked: false }, {id: 3,isChecked: true }]"
       [checked]="data.isChecked == true"
       [(ngModel)]="data.isChecked"
       (change)="onCheckboxValueChange(data)">