Reputation: 123
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
Upvotes: 1
Views: 561
Reputation: 867
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
Upvotes: 1