How to get checkbox data in angular material

五迷三道 提交于 2019-12-20 01:40:03

问题


I want to get the all checkboxes items when user selects, now am getting the data But the problem is that the checkbox don't change, I mean that when I click the checkbox, if the initial state is checked, always remain checked and vice versa.

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

回答1:


I think you are overcomplicating things.

Modify your array so that each entry has a name and a checked property, and bind the checkboxes to them with [(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




回答2:


Using reactive forms would be easier :

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])));

The template :

<ng-container [formGroup]="form">
  <mat-checkbox *ngFor="let controlName of controlNames" [formControlName]="controlName">{{controlName}}</mat-checkbox>
</ng-container>

Here is an edit of your stackblitz.



来源:https://stackoverflow.com/questions/50407776/how-to-get-checkbox-data-in-angular-material

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!