问题
In my project I have created Select/ Unselect Checkbox functionality
. There are multiple different checkbox
on same page. How can I separate Select All
Checkbox functionality so that its only applied to its values.
Demo code
https://stackblitz.com/edit/angular-material-select-all-bx4qen?file=src%2Fapp%2Fapp.component.html
Note - There are atleast 8 such separate Checkbox in my project. I am looking for optimal solution
回答1:
you need to have different variable for each check box group. but since you have mentioned that , there are many checkboxes.
here is the optimized solution.
Introduce an array for representation, that way you need to change anything on html if you introduce new checkbox and you can separate ngModel even for sub checkboxes as well.
export class AppComponent {
selected: boolean = false;
checkboxes: any = [
{
label: "First",
root: false,
create: false,
update: false,
delete: false
},
{
label: "Second",
root: false,
create: false,
update: false,
delete: false
},
{ label: "Third", root: false, create: false, update: false, delete: false }
];
handeClick(checkbox): void {
checkbox.root = !checkbox.root;
checkbox.create = checkbox.root;
checkbox.update = checkbox.root;
checkbox.delete = checkbox.root;
}
}
|<div *ngFor="let checkbox of checkboxes">
<h2>{{checkbox.label}}</h2>
<mat-checkbox (ngModelChange)="handeClick(checkbox)" [ngModel]="checkbox.root">Check/ Uncheck</mat-checkbox>
<mat-checkbox [ngModel]="checkbox.create">Create</mat-checkbox>
<mat-checkbox [ngModel]="checkbox.update">Update</mat-checkbox>
<mat-checkbox [ngModel]="checkbox.delete">Delete</mat-checkbox>
</div>
here is the demo - https://stackblitz.com/edit/angular-material-select-all-qoehwy?file=src%2Fapp%2Fapp.component.html
来源:https://stackoverflow.com/questions/65244092/angular-checkbox-unique-selection