我有一个复选框列表。在此,我想在选中列表中的任何项目时禁用其他复选框。现在,如果我取消选中该项目,那么现在需要启用所有复选框。
这是 plunker - http://plnkr.co/edit/5FykLiZBQtQb2b31D9kE?p=preview
取消选中任何复选框时,其余所有复选框仍处于禁用状态。我该怎么做?
这是应用程序文件-
import {bootstrap} from 'angular2/platform/browser';
import {Component} from 'angular2/core'
@Component({
selector: 'my-app',
template: `
<h2>{{title}}</h2>
<label *ngFor="let cb of checkboxes">
{{cb.label}}<input [disabled]="cb.status" type="checkbox"
[(ngModel)]="cb.state" (click)="buttonState(cb.id)">
</label><br />
{{debug}}
`
})
class App {
title = "Angular 2 - enable button based on checkboxes";
checkboxes = [{label: 'one',id: '0', status: ''},{label: 'two', id: '1', status:''},{label: 'three', id: '2', status: ''}];
constructor() {
//this.buttonState();
console.log("constructor called"); }
buttonState(id) {
console.log( id + "Button State Called");
//return this.checkboxes[0].status;
if(this.checkboxes[id].state == true){
this.checkboxes[id].status = true;
this.checkboxes[(id+1)%3].status = false;
this.checkboxes[(id+2)%3].status = false;
console.log("True Block");
}
else (this.checkboxes[id].state == false) {
this.checkboxes[id].status = false;
this.checkboxes[(id+1)%3].status = true;
this.checkboxes[(id+2)%3].status = true;
console.log("False Block");
}
}
get debug() {
return JSON.stringify(this.checkboxes);
}
}
bootstrap(App, [])
.catch(err => console.error(err));
改用这个buttonState
函数:
buttonState(id) {
this.checkboxes.forEach(function(checkbox) {
if (checkbox.id !== id) {
checkbox.status = !checkbox.status;
}
})
}
参见 plunker 示例:http://plnkr.co/edit/ASzUR2jawpbifvwBXNO9?p=preview
另一种解决方案。不是一个好...但是,如果您发现任何问题,您仍然可以尝试
class App {
title = "Angular 2 - enable button based on checkboxes";
checkboxes = [{label: 'one',id: '0', status: ''},{label: 'two', id: '1', status:''},{label: 'three', id: '2', status: ''}];
constructor() {
console.log("constructor called");
}
buttonState(id) {
console.log( this.checkboxes[id].state + "Button State Called");
//return this.checkboxes[0].status;
if(this.checkboxes[id].state == true ){
this.checkboxes[id].status = false;
this.checkboxes[(id+1)%3].status = false;
this.checkboxes[(id+2)%3].status = false;
console.log("True Block");
}
else if(this.checkboxes[id].state == false || this.checkboxes[id].state == undefined) {
this.checkboxes[id].status = false;
this.checkboxes[(id+1)%3].status = true;
this.checkboxes[(id+2)%3].status = true;
console.log("False Block");
}
}
http://plnkr.co/edit/mAvSQbyP9oh84LWfpGIm?p=preview