我正在使用 Angular 15,并使用“全选”选项创建此多重选择垫选择下拉列表:
<mat-form-field appearance="fill">
<mat-label>Select Months</mat-label>
<mat-select multiple matNativeControl required (selectionChange)="onMonthsSelected($event)" [formControl]="selected_months">
<mat-option [value]="0" (click)="selectAllMonths(ev)" #ev>Select All</mat-option>
<mat-option *ngFor="let month of months" [value]="month">
{{month}}
</mat-option>
</mat-select>
</mat-form-field>
在 TS 文件中:
months:any[] = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
selected_months = new FormControl();
onMonthsSelected($event: any) {
// What to do?
}
selectAllMonths(ev:any) {
if (ev._selected) {
this.selected_months = this.months;
ev._selected = true;
}
if (!ev._selected) {
this._selected_months.setValue([]);
}
}
我正在寻求的功能是,当通过选择每个“月”来选择所有选项时,将选中“全选”选项。如果在选择所有选项后取消选择一个选项,则全选选项将被取消选中。我不知道如何通过函数来实现这个功能
onMonthsSelected
,有什么想法吗?
您需要通过
@ViewChild
装饰器获取组件中全选选项的引用。
onMonthsSelected
应防止选择/取消选择“全选”选项时发生该事件。
将所选月份
$event.value
与months
数组进行比较,如果全部匹配则调用.select()
API,否则调用.deselect()
垫选项API。
import { ViewChild } from '@angular/core';
@ViewChild('ev') selectAllOption!: MatOption;
onMonthsSelected($event: any) {
if ($event.value && $event.value[0] === 0) return;
if (
this.months.length == $event.value.length &&
this.months.every((x, i) => x === $event.value[i])
)
this.selectAllOption.select(false);
else this.selectAllOption.deselect(false);
}