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