javascript - 未选中复选框时如何在javascript中执行弹出操作?

标签 javascript angular typescript angular6

我只有两个复选框,其代码如下所示:

<div *ngFor="let item of documents">
   <label>
   <input type="checkbox" value="{{item.docId}}" [(ngModel)]="item.checked" [name]="item.docName"
   (change)="editPartyRolesSubmit($event)"
   />
   <span innerHTML="{{item.docName}}"></span>
   </label>
</div>

这里我只使用了两个复选框: enter image description here

editPartyRolesSubmit($event) 调用的函数是:

public documents: Array<Document> = []
public onlyTruedocuments: Array<Document> = [];

    editPartyRolesSubmit(event) {

      this.documents.filter(x => x.checked).map(x => {
        console.log("entered in check");
        this.onlyTruedocuments.push(x);
          console.log(x);
        })
    }

Json 数据被推送了 3 次,虽然我只是点击了两次,但它应该只被推送了两次。

enter image description here

但是当我在 .html 页面中打印它们时,虽然复选框是两个,但它被打印了三次:

<li *ngFor="let ot of onlyTruedocuments; index as i">

     {{ot.docName}}
</li> 

它是这样打印的:

enter image description here

如何删除这些冗余数据?

最佳答案

如果我理解正确的话,我会这样做,

我使用了 (ngModelChange) 而不是 (change)

我已将当前 item 传递给 ngModelChange 函数。

HTML:

<div *ngFor="let item of documents">
    <label>
   <input type="checkbox" value="{{item.docId}}" [(ngModel)]="item.checked" [name]="item.docName"
   (ngModelChange)="editPartyRolesSubmit($event,item)"/> // will pass an item to the function 
   <span innerHTML="{{item.docName}}"></span>
   </label>
</div>

<li *ngFor="let ot of onlyTruedocuments; index as i">
     {{ot.docName}}
</li>

TS 文件:

export class YourComponent {
  documents = [{
    docId: 1,
    checked: false,
    docName: 'Prashant'

  },
  {
    docId: 2,
    checked: false,
    docName: 'Venkat'

  }
    , {
    docId: 2,
    checked: false,
    docName: 'Perry'

  }];

  public onlyTruedocuments: any = [];

  editPartyRolesSubmit(event, obj) {
    // Take the index of an Item checked
    let index = this.onlyTruedocuments.indexOf(obj);

    // Check for event i.e it is checked or unchecked
    if (event) {
      if (index == -1) {
        // If the index is -1 then that means its not a duplicate so push into an array
        this.onlyTruedocuments.push(obj);
      }
    }
    else {
      // If it is unchecked then we surely know that the item has to be removed from the array so by an index of the particular item we can [splice][1] the item
      this.onlyTruedocuments.splice(index, 1)
    }
  }
}

无需过滤源数组即可获取勾选项。

工作 StackBlitz示例数据示例。

关于javascript - 未选中复选框时如何在javascript中执行弹出操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53360180/

相关文章:

javascript - Dropzone.js 与 Laravel 得到 500(内部服务器错误)

Angular 2 属性在类型 'CustomEvent' 上不存在

css - Angular/SCSS : animation not applied on element

javascript - screen.getByText 不是函数

javascript - Three.jscubeCamera envmap 不工作

javascript - Vanilla JS 事件委托(delegate) - 处理目标元素的子元素

javascript - 将远程 2 个 Zip 文件合并到新的 Zip 文件中

javascript - 如何从 Javascript 函数执行 Angular 函数?

module - 为什么环境声明使用命名空间和模块?

javascript - 在对象树中查找根和任意对象之间的对象