6

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

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your answer, Is it possible with formControlName instead of ngModel ?
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.