角度垫子-全选"可进行多个选择



我正在尝试为角度多个选择做全部选择,它适用于一个选择,但是当你有多个选择时,我如何让它工作? 当我为第二个输入添加全选时,它会在第一个输入时选择所有

活动.ts

@ViewChild('mySel') skillSel: MatSelect;
toggleAllSelection() {
this.allSelected = !this.allSelected;
if (this.allSelected) {
this.skillSel.options.forEach( (item : MatOption) => item.select());
} else {
this.skillSel.options.forEach( (item : MatOption) => {item.deselect()});
}
}

活动.html

<mat-select #mySel multiple formControlName="Branch">
<mat-option [value]="0" (click)="toggleAllSelection()">All items</mat-option>
<mat-option *ngFor="let item of centers" [value]="item.centerCode">{{item.address}}</mat-option>
</mat-select>
<mat-select #mySel multiple formControlName="categoryDescriptions">
<mat-option [value]="0" (click)="toggleAllSelection()">All items</mat-option>
<mat-option *ngFor="let item of categories" [value]="item.description">{{item.description}}</mat-option>
</mat-select>

问题是你有一个变量allSelected来控制两个mat-select框,并且你还为两个mat-select框提供了相同的 IDmySel。这就是为什么当您在第二个选项中使用全选选项时,它会在第一个mat-select选择所有选项。

要解决此问题,请为每个mat-select提供不同的 ID,例如mySelBranchmySelCategory

<mat-form-field appearance="fill">
<mat-label>Branch</mat-label>
<mat-select #mySelBranch [formControl]="branch" multiple>
<mat-option [value]="0" (click)="toggleAllSelection(mySel)">All items</mat-option>
<mat-option *ngFor="let branch of branchList" [value]="branch">{{branch}}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="fill">
<mat-label>Category</mat-label>
<mat-select #mySelCategory [formControl]="categoryDescriptions" multiple>
<mat-option [value]="0" (click)="toggleAllSelection(mySel2)">All items</mat-option>
<mat-option *ngFor="let category of categoryList" [value]="category">{{category}}</mat-option>
</mat-select>
</mat-form-field>

你会注意到我也把调用改成了toggleAllSelection- 它现在将 mat-select 作为参数传入。

toggleAllSelection已更改为:

toggleAllSelection(matSelect: MatSelect) {
const isSelected: boolean = matSelect.options
// The "Select All" item has the value 0, so find that one
.filter((item: MatOption) => item.value === 0)
// Get the value of the property 'selected' (this tells us whether "Select All" is selected or not)
.map((item: MatOption) => item.selected)
// Get the first element (there should only be 1 option with the value 0 in the select)
[0];
if (isSelected) {
matSelect.options.forEach((item: MatOption) => item.select());
} else {
matSelect.options.forEach((item: MatOption) => item.deselect());
} 
}

函数的第一部分查看作为参数传入的mat-select的选项,并找到值0的选项(由于您定义 HTML 的方式,"全选"选项始终具有值0)。然后,它获取属性名称selected的值(这将true为选中"全选",如果取消选择,则为 false)。由于这是一个数组,然后它使用[0]来获取第一项(由于使用了filter函数,此时数组中应该只有一个项目:

const isSelected: boolean = matSelect.options
.filter((item: MatOption) => item.value === 0)
.map((item: MatOption) => item.selected)[0];

TypeScript 类中不再需要以下变量:

@ViewChild("mySel") skillSel: MatSelect;
allSelected = false;

请参阅此StackBlitz进行演示。

最新更新