选择所有垫选项并取消选择所有 [英] Select All mat option and deselect All
本文介绍了选择所有垫选项并取消选择所有的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有如下场景:
我要实现的是:
- 当用户点击全部时,所有选项都将被选中,当用户再次点击全部时,所有选项都将被取消选择.
- 如果所有选项被选中并且用户点击了除
All
之外的任何其他复选框,那么All和点击的复选框将被取消选择. - 当用户一一选择 4 个选项时,应选择全部.
- When user click on All then all options shall be selected and when user click All again then all options shall be deselcted.
- If All option is checked and user click any other checkbox than
All
then All and clicked checkbox shall be deselected. - When user selects 4 options one by one then All shall be selected.
HTML 文件
<mat-select placeholder="User Type" formControlName="UserType" multiple>
<mat-option *ngFor="let filters of userTypeFilters" [value]="filters.key">
{{filters.value}}
</mat-option>
<mat-option #allSelected (click)="toggleAllSelection()" [value]="0">All</mat-option>
</mat-select>
TS 文件
this.searchUserForm = this.fb.group({
userType: new FormControl('')
});
userTypeFilters = [
{
key: 1, value: 'Value 1',
},
{
key: 2, value: 'Value 2',
},
{
key: 3, value: 'Value 3',
},
{
key: 4, value: 'Value 4',
}
]
toggleAllSelection() {
if (this.allSelected.selected) {
this.searchUserForm.controls.userType
.patchValue([...this.userTypeFilters.map(item => item.key), 0]);
} else {
this.searchUserForm.controls.userType.patchValue([]);
}
}
现在,如何实现第二和第三点
Stackblitz 是:https://stackblitz.com/edit/angular-material-with-angular-v5-znfehg?file=app/app.component.html
Stackblitz is: https://stackblitz.com/edit/angular-material-with-angular-v5-znfehg?file=app/app.component.html
推荐答案
使用如下代码创建函数点击每个 mat-option
和 select()/deselect()
所有选项:
Use code as below create function on click each mat-option
and select()/deselect()
all option:
参见 stackblitz:https://stackblitz.com/edit/angular-material-with-angular-v5-jsgvx6?file=app/app.component.html
See stackblitz:https://stackblitz.com/edit/angular-material-with-angular-v5-jsgvx6?file=app/app.component.html
TS:
togglePerOne(all){
if (this.allSelected.selected) {
this.allSelected.deselect();
return false;
}
if(this.searchUserForm.controls.userType.value.length==this.userTypeFilters.length)
this.allSelected.select();
}
toggleAllSelection() {
if (this.allSelected.selected) {
this.searchUserForm.controls.userType
.patchValue([...this.userTypeFilters.map(item => item.key), 0]);
} else {
this.searchUserForm.controls.userType.patchValue([]);
}
}
HTML:
<form [formGroup]="searchUserForm" fxFlex fxLayout="column" autocomplete="off" style="margin: 30px">
<mat-select placeholder="User Type" formControlName="userType" multiple>
<mat-option *ngFor="let filters of userTypeFilters" [value]="filters.key" (click)="togglePerOne(allSelected.viewValue)">
{{filters.value}}
</mat-option>
<mat-option #allSelected (click)="toggleAllSelection()" [value]="0">All</mat-option>
</mat-select>
</form>
这篇关于选择所有垫选项并取消选择所有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文