我有一个 Angular Material 下拉菜单,我需要根据从另一个下拉菜单中选择的值来禁用该下拉列表中的特定元素。
这是两个下拉列表的 HTML:
<mat-form-field>
<mat-label>Choose an option</mat-label>
<mat-select id="lineOfBusiness" formControlName="lineOfBusiness">
<mat-option value="commercial">Commercial</mat-option>
<mat-option value="residential" >Residential</mat-option>
<mat-option value="industrial">Industrial</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>Choose an option</mat-label>
<mat-select id="psv" formControlName="psv">
<mat-option value="inclinometer">Inclinometer</mat-option>
<mat-option value="heil" >Heil</mat-option>
<mat-option value="radar">Radar</mat-option>
<mat-option value="hydraulics">Hydraulics</mat-option>
<mat-option value="coretex">Coretex</mat-option>
</mat-select>
</mat-form-field>
例如,逻辑如下所示: 如果 'lineOfBusiness' = 'commercial',则在 'psv' 下拉列表中,应禁用 'radar'。
在我的 form.component.ts 文件中,我有这个函数,它执行时没有错误,但没有禁用所需的选项。
disableOption(optionValue: string): void {
console.log("Disabling " + optionValue);
const psvControl = this.reactiveForm.get('psv');
if (psvControl) {
const option = psvControl.get(optionValue);
if (option) {
option.disable();
}
}
}
我做错了什么?
关键概念:
通过模板引用变量获取
psv
控件的MatSelect DOM元素。
订阅
lineOfBusiness
控件的 valueChanges
以在 disableOption
值更改时触发 lineOfBusiness
方法。
当为
lineOfBusiness
控件选择值“commercial”时,将 mat-option 设置为禁用,反之亦然。
import { Component, ViewChild } from '@angular/core';
import { Subject, takeUntil } from 'rxjs';
import { MatSelect } from '@angular/material/select';
private destroy$ = new Subject();
@ViewChild('psvSelect') psvSelect!: MatSelect;
ngAfterViewInit() {
this.reactiveForm.controls.lineOfBusiness.valueChanges
.pipe(takeUntil(this.destroy$))
.subscribe((value) => {
this.disableOption(value);
});
}
disableOption(optionValue: string): void {
console.log('Disabling ' + optionValue);
if (optionValue === 'commercial')
this.psvSelect.options.find((x) => x.value == 'radar')!.disabled = true;
else
this.psvSelect.options.find((x) => x.value == 'radar')!.disabled = false;
}
ngOnDestroy() {
this.destroy$.next(true);
this.destroy$.complete();
}
您需要声明模板引用变量
#psvSelect
,如下所示:
<mat-select id="psv" formControlName="psv" #psvSelect>
...
</mat-select>