垫选择选择更改获取组角度

问题描述 投票:0回答:4

我有两个

mat-select
组来控制
mat-optgroup
它有一个事件处理程序
(selectionChange)="applicationSelected($event.value, i)

如何检测从哪个组中选择了选项?

angular angular-material
4个回答
7
投票

没有一种简单、直接的方法可以从

selectionChange
事件中了解该群体。它只告诉您源 (MatSelect) 和选定的值。但是 MatOption 的
onSelectionChange
事件使您可以访问 MatOption,进而可以访问 MatOptionGroup。例如:

<mat-option (onSelectionChange)="optionSelected($event)" ...>...</mat-option>

optionSelected(event: MatOptionSelectionChange) {
    console.log(event.source.group.label);
}

3
投票

我也遇到了这个问题,但请记住,onSelectionChanged() 的预期行为如下:不仅在选择选项时触发选择更改事件,而且在取消选择选项时也会触发选择更改事件。因此,当选择一个选项时,会触发两个事件:用户选择和现在取消选择的选项。 因此,您将看到 2 个事件被触发。其中第一个是所需的。您可以查看 event.isUserInput 是否设置为 true(所需事件),并将 group.name 发送到事件处理程序: 在你的组件 html 中:

<mat-select formControlName="category" required> <mat-optgroup *ngFor="let group of categoryGroups" [label]="group.name"> <mat-option *ngFor="let category of group.options" [value]="category.value" (onSelectionChange)="onCategorySelection($event, group.name)"> {{category.viewValue}} </mat-option> </mat-optgroup> </mat-select>

以及你在组件类中绑定事件的函数:

onCategorySelection(event: MatOptionSelectionChange, groupName: string) { if (event.isUserInput) { this.groupName = groupName; // event.source.group.label; } }


0
投票

这是我的解决方案:

<mat-form-field > <mat-label>Filter By</mat-label> <mat-select panelClass="" #choosedValue (valueChange)="doSomething1(choosedValue.value)" > <mat-option >-- None --</mat-option> <mat-optgroup #group1 *ngFor="let group of filterData" [label]="group.viewValue" style = "background-color: #0c5460"> <mat-option #mmm *ngFor="let option of group.options" [value]="{value: option.value, groupValue: group.value}" > {{option.viewValue}} </mat-option> </mat-optgroup> </mat-select> </mat-form-field>

和功能:

doSomething1(value: any){ console.log("do something with ", value);//result: {value: "Honda", groupValue: "cars"} }



0
投票
event.source.group.label

给了我一个错误,我发现

selected
里面的值是,event.source.selected.group.label
<mat-option (onSelectionChange)="optionSelected($event)" ...>...</mat-option>

optionSelected(event: MatOptionSelectionChange) {
    console.log(event.source.selected.group.label);
}

© www.soinside.com 2019 - 2024. All rights reserved.