如何在角材料中获取复选框数据

时间:2018-05-18 09:12:16

标签: angular material-design angular-material

我希望在用户选择时获取所有复选框项目,现在我正在获取数据但问题是复选框没有更改,我的意思是当我单击复选框时,如果检查初始状态,则始终保持检查,反之亦然。

this.settings_data = ["one", "two", "three", "four", "five"];

<div class="settings_head" fxFlex="50" *ngFor="let item of settings_data">
  <mat-checkbox formControlName="settingsCheckboxvalues" (ngModelChange)="seleteditems($event,item)">{{item}}</mat-checkbox>
</div>



seleteditems(event, value) {
  this.allitems.push(value);
}

2 个答案:

答案 0 :(得分:3)

我认为你过于复杂了。

修改数组,使每个条目都有namechecked属性,并使用[(ngModel)]

将复选框绑定到它们

<强> TS

array = [
    {
      name: 'one',
      checked: false
    },
    {
      name: 'two',
      checked: false
    },
    {
      name: 'three',
      checked: false
    },
    {
      name: 'four',
      checked: false
    },
    {
      name: 'five',
      checked: false
    }
  ]
  getCheckboxes() {
    console.log(this.array.filter(x => x.checked === true).map(x => x.name));
  }

<强> HTML

<div *ngFor="let item of array">
    <mat-checkbox [(ngModel)]="item.checked" (change)="getCheckboxes()">{{item.name}}</mat-checkbox>
</div>

Demo

答案 1 :(得分:1)

使用反应形式会更容易:


    - name: Start and enable the service
      service:
        name: mysql
        state: started
        enabled: yes
    - name: Ensure mysql port is started
      wait_for:
        port: 3306
        delay: 3
        timeout: 300

模板:

this.form = this.fb.group({
      'one': false,
      'two': false,
      'three': false,
      'four': false
    })
    this.controlNames = Object.keys(this.form.controls).map(_=>_)
    this.selectedNames$ = this.form.valueChanges.pipe(map(v => Object.keys(v).filter(k => v[k])));

Here is an edit of your stackblitz.