javascript - 在复选框的更改事件中添加和删除数组内的值

标签 javascript angular typescript checkbox angular6

在我的 Angular 应用程序中,我正在创建一个复选框并捕获复选框更改事件并将选中的值推送到数组中。

这里,如果我们取消选中该复选框,则 obj 也会被推送到数组中..

如果取消选中复选框,如何从数组中删除obj..

HTML:

<div *ngFor="let item of order; let i = index">
  <input type="checkbox" [id]="item+i" [name]="item"[(ngModel)]="item.Checked" (change)="getCheckboxValues(item)">
   <label [for]="item+i"> {{item}} </label>
</div>

T:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  order = ['One','Two','Three','Four'];

  newArray : any = [];

  //Checkbox Change detecting function
  getCheckboxValues(data) {
    let obj = {
      "order" : data
    }

   // Pushing the object into array
    this.newArray.push(obj);

    //Duplicates the obj if we uncheck it
    //How to remove the value from array if we uncheck it
    console.log(this.newArray);
  }

}

我用上面的方法解决的问题在链接https://stackblitz.com/edit/angular-9pt9sn

请帮我删除``newArray```中未经检查的值..

最佳答案

更改为(ngModelChange)="getCheckboxValues($event,item)"

以及根据复选框的选中和取消选中来添加(如果不存在)和删除(如果元素存在)的函数

  //Checkbox Change detecting function
  getCheckboxValues(ev, data) {
    let obj = {
      "order" : data
    }

    if(ev.target.checked){
      // Pushing the object into array
      this.newArray.push(obj);

    }else {
      let removeIndex = this.newArray.findIndex(itm => itm.order===data);

      if(removeIndex !== -1)
        this.newArray.splice(removeIndex,1);
    }

    //Duplicates the obj if we uncheck it
    //How to remove the value from array if we uncheck it
    console.log(this.newArray);
  }

链接 https://stackblitz.com/edit/angular-5jamcr

关于javascript - 在复选框的更改事件中添加和删除数组内的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53478277/

相关文章:

javascript - 给每个 CouchDB 用户一个单独的数据库是好的做法吗?

javascript - 如何在 JavaScript 中使用 const 和 while 循环

javascript - Angular SVG 路径不可见

javascript - TypeScript 中的 RSA 加密/解密

javascript - 从 Dictionary React js 中删除项目的最佳方法

javascript - 字段变化触发功能

angular - Angular 中有 $parent 等价物吗?

javascript - 如何从 Promise 解析中获取值?

angular - 如何在 Angular Component Router 中使用参数定义默认路由?

javascript - 检查 json 树是否没有更多的 child