2016-06-07 50 views
1

我有一個複選框列表。在此我想從列表中選中任何項目時禁用其他複選框。現在,如果我取消選中該項目,那麼現在需要啓用所有複選框。如何通過單擊Angular2中的列表中的複選框來禁用其他複選框

這是plunker - http://plnkr.co/edit/5FykLiZBQtQb2b31D9kE?p=preview

在取消選中所有其他複選框被仍被禁用任何複選框。請給點建議。這個怎麼做?

在此先感謝。 這是app.ts文件 -

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)); 

回答

1

另一solution..not一個好......但如果您發現任何問題,仍然可以嘗試。

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

相關問題