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);
}
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With