Reputation: 169
I n my angular app. I have multiple checkboxes. I want to use on checkbox to select and unselect all the remaining checkboxes. my data is from the backened. Please guide mo on how to implement it.
HTML
<ul>
<li> <input type="checkbox" [(ngModel)]="selectedAll" (change)="selectAll();"/>
</li>
<li *ngFor="let n of names">
<input type="checkbox" [(ngModel)]="n.checked" (click)="onChecked($event, n.test);">
{{n.name}}
</li>
</ul>
TS
onChecked(event, value) {
if (event.target.checked) {
this.data.push(value);
} else {
const item = this.data.findIndex(x => x === value);
this.data.splice(this.data.indexOf(item), 1);
}
}
Upvotes: 1
Views: 1600
Reputation: 1435
You need to update the Array
selectAll() {
this.names.forEach(name => name.checked = selctedAll)
// bulk update request
}
you can perform bulk update request once forEach()
is over.
Upvotes: 0
Reputation: 17610
Demo below code checked unchecked all
selectAll(){
this.names.forEach(n=>{n.checked=this.selectedAll});
}
or
selectAll(){
this.names.map(a=>a.checked=this.selectedAll);
}
Upvotes: 2
Reputation: 1212
component.html
<ul>
<li> <input type="checkbox" [(ngModel)]="checkAll" (change)="selectAll(checkAll);"/> {{ checkAll ? 'Deselect All': 'Select All'}}
</li>
<li *ngFor="let n of names">
<input type="checkbox" [(ngModel)]="n.checked" (click)="onChecked(n);">
{{n.name}}
</li>
</ul>
compoenent.ts
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular ' + VERSION.major;
checkAll: false;
names = [
{
name: 'name 1',
checked : false
},
{
name: 'name 2',
checked : false
},
{
name: 'name 3',
checked : false
},
{
name: 'name 4',
checked : false
}
];
selectAll(checkAll) {
if(checkAll) {
this.names.forEach((element)=> {
element.checked= true;
});
} else {
this.names.forEach((element)=> {
element.checked= false;
});
}
}
onChecked(obj) {
const index = this.names.indexOf(obj);
this.names[index].checked = true;
}
}
Upvotes: 0
Reputation: 1627
If your selectedAll
is boolean, you can simply use a method like this
selectAll() {
this.names.forEach(name => {
name.checked = this.selectedAll;
});
}
And in your html
<li> <input type="checkbox" [(ngModel)]="selectedAll" (change)="selectAll($event);"/></li>
Upvotes: 0