Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get checkbox data in angular material

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);
}
like image 696
vinaykumar0459 Avatar asked May 18 '18 09:05

vinaykumar0459


2 Answers

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

like image 51
bugs Avatar answered Nov 15 '22 07:11

bugs


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.

like image 45
ibenjelloun Avatar answered Nov 15 '22 07:11

ibenjelloun