Man*_*gan 1 javascript checkbox typescript angular angular6
在我的角度应用程序中,我正在制作一个复选框并捕获复选框更改事件并将选中的值推入数组中。
在这里,如果我们取消选中该复选框,则 obj 也会被推送到数组中。
如果取消选中如何从数组中删除obj。
网页:
<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>
Run Code Online (Sandbox Code Playgroud)
时间:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我用上面的方法解决的问题在链接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);
}
Run Code Online (Sandbox Code Playgroud)
链接https://stackblitz.com/edit/angular-5jamcr
| 归档时间: |
|
| 查看次数: |
8612 次 |
| 最近记录: |