简体   繁体   中英

How to push and pop items to/from an array in mat-checkbox change in Angular?

I have an array with 5 items. These array items are populated in mat-checkbox and I need to push/pop items to a new array when checkbox checked or unchecked. This is my code.

HTML

<div>
  <mat-checkbox *ngFor="let a of arr1">
    {{a.value}}</mat-checkbox>
</div>

TS

export class AppComponent  {

arr1 = [
{ type: "A", value: "a" },
{ type: "B", value: "b" },
{ type: "C", value: "c" },
{ type: "D", value: "d" },
{ type: "E", value: "e" }
];
arr2: any= [];

constructor() {}
}

Can anyone give me a better solution for this? Stackblitz link

You can use $event on mat-checkbox to push/pop items to new array like below.

HTML

<div>
  <mat-checkbox *ngFor="let a of arr1" 
    (change)="onCheckboxChecked($event, a)">
    {{a.value}}</mat-checkbox>
</div>

TS

onCheckboxChecked(event, element) {

  if (event.checked) {

    this.arr2.push(element);
  } else {

    let index = this.arr2.indexOf(element);
    if (index > -1) {
      this.arr2.splice(index, 1);
    }
  }
  console.log(JSON.stringify(this.arr2));
}

See your Stackblitz link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM