我只有两个复选框,其代码如下所示:
<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>
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 次,虽然我只是点击了两次,但它应该只被推送了两次。
但是当我在 .html 页面中打印它们时,虽然复选框是两个,但它被打印了三次:
<li *ngFor="let ot of onlyTruedocuments; index as i">
{{ot.docName}}
</li>
它是这样打印的:
如何删除这些冗余数据?
最佳答案
如果我理解正确的话,我会这样做,
我使用了 (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/