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

}

I am checking the length of selectedFileList to check if more than 1 cb is selected but unable to do so please help.

button should be enabled only if 1 cb is selected and disabled if 0 or more than 1 selected

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

2
  • 1
    It seems like you should be using a radio button Commented Mar 12, 2019 at 12:29
  • @Explosion Pills no functionality does not allow that Commented Mar 12, 2019 at 14:04

1 Answer 1

1

Change

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

to

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

also you assign (not check) 1 in this.selectedFileList.length=1

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.