import { Component } from '@angular/core';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {



title = "Angular 2 - enable button based on checkboxes";
  checkboxes = [{label: 'one',selected:false},


  {label: 'two',selected:false}

  ];
selectedFileList:any[]=[];
checkClicked(event: Event, i) {
    if (event.target['checked']) {

      this.selectedFileList.push(i);

      console.log("selected checkBox is: "+this.selectedFileList);

    }
    else {
      let index = this.selectedFileList.indexOf(i);
      if (index !== -1) this.selectedFileList.splice(index, 1);
      console.log("inside else")
      this.selectedFileList=[];

    }
   }


  constructor() { console.clear(); }
  buttonState() {
    // console.log('buttonState() called');
    return !this.checkboxes.some(cb => cb.selected) && (this.selectedFileList.length=1);
  }
  get debug() {
    return JSON.stringify(this.checkboxes);
  }

}


我正在检查selectedFileList的长度,以检查是否选择了超过1个cb,但无法这样做,请帮助。

仅在选择1 cb的情况下应启用按钮,而在选择0或大于1的情况下应禁用按钮

stackBlitz:
https://stackblitz.com/edit/angular-cjccyp?file=src%2Fapp%2Fapp.component.ts

最佳答案

更改

!this.checkboxes.some(cb => cb.selected)




this.checkboxes.filter(cb => cb.selected).length === 1


您也在1中分配(不检查)this.selectedFileList.length=1

关于javascript - 如果仅选中1个复选框,则启用按钮。否则禁用按钮,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55121446/

10-13 02:01