简体   繁体   English

如何在 Angular 中的 mat-checkbox 更改中向/从数组推送和弹出项目?

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

I have an array with 5 items.我有一个包含 5 个项目的数组。 These array items are populated in mat-checkbox and I need to push/pop items to a new array when checkbox checked or unchecked.这些数组项目填充在mat-checkbox ,当复选框选中或取消选中时,我需要将项目推送/弹出到新数组。 This is my code.这是我的代码。

HTML HTML

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

TS 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.您可以在mat-checkbox上使用$event将项目推送/弹出到新数组,如下所示。

HTML HTML

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

TS 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查看您的Stackblitz 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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