我正在使用多个复选框,单击任何复选框时,如果选中 true,则需要将值推送到数组中;如果选中 false,则需要从数组中删除。
有什么方法可以像jquery一样检查点击时复选框是否被选中或取消选中?
进一步评论:
HTML 元素:
<input type="checkbox" (click)="onClick($event)" />
打字稿代码:
onClick(event: any) {
console.log(event); //you can explore the event object and use the values as per requirement
}
查看这篇类似的文章,该文章解决了多个复选框的问题。 Angular-2-获取多个选中复选框的值
我在这里包含了 angular2 中复选框状态的简单实现
import {Component, NgModule } from '@angular/core';
@Component({
selector: 'test-app',
template: `
<label for="options">Options :</label>
<div *ngFor="let cbItem of cbArr">
<label>
<input type="checkbox"
name="options"
value="{{cbItem}}"
[checked]="cbChecked.indexOf(cbItem) >= 0"
(change)="updateCheckedOptions(cbItem, $event)"/>
{{cbItem}}
</label>
</div>
<button (click)="updateOptions()">Post</button>
`
})
export class TestComponent{
cbArr: string[];
cbChecked: string[];
constructor() {
this.cbArr = ['OptionA', 'OptionB', 'OptionC'];
this.cbChecked = ['OptionB'];
}
updateCheckedOptions(chBox, event) {
var cbIdx = this.cbChecked.indexOf(chBox);
if(event.target.checked) {
if(cbIdx < 0 )
this.cbChecked.push(chBox);
} else {
if(cbIdx >= 0 )
this.cbChecked.splice(cbIdx,1);
}
}
updateOptions() {
console.log(this.cbChecked);
}
}
这里cbArr存储所需的值或选项,cbChecked存储选定的值。更改复选框值时,cbChecked 会更新,复选框项目的 ID 会更新到其中,最后单击“发布”按钮,您可以简单地打印出所选项目列表的 cbChecked 值。