angular - Angular - Mat 选项选择的值不起作用
问题描述
我们有两个表单字段,我们需要根据从第一个字段中选择的值禁用或启用第二个字段。在第一个字段中,我们有 5 个值,例如 'a'、'b'、'c'、'd'、'e'。用户可以从这 5 个值中选择全部或不选择。
如果用户选择“C”,我们需要启用第二个表单字段,否则它应该被禁用。
有人可以帮我写这个逻辑。
<mat-form-field>
<mat-label>Technology Options<mat-icon class="required">star_rate</mat-icon></mat-label>
<mat-select multiple formControlName="TechnologyTypeId" [value]="mResponse.TechnologyTypeId">
<mat-option *ngFor="let item of TechnologyTypes"
[value]="item.TechnologyTypeId"
(selectionChange)="onSelection($event)">
{{ item.OutputText }}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>Language Types<mat-icon class="required">star_rate</mat-icon></mat-label>
<mat-select multiple formControlName="LanguageTypeId">
<mat-option *ngFor="let item of LanguageTypes"
[value]="item.LanguageId">
{{ item.LanguageText }}
</mat-option>
</mat-select>
</mat-form-field>
解决方案
在您的打字稿代码上(假设您的 formGroup 被称为_form
:
import {Subject} form 'rxjs';
import {takeUntil} form 'rxjs/operators';
...
_form: FormGroup;
// best practice: unsubscribe from all your observables when the component is destroyed
private _destroy$ = new Subject<void>();
...
constructor(private _fb: FormBuilder) {
this._form = this._fb.group({
...
TechnologyTypeId: null,
LanguageTypeId: {value: null, disabled: true}
...
})
}
ngAfterViewInit() {
this._form.get('TechnologyTypeId').valueChanges
.pipe(takeUntil(this._destroy$))
.subscribe((value: string) => {
if(value === '3rd value') {
this._form.get('LanguageTypeId').enable();
} else {
this._form.get('LanguageTypeId').disable();
}
});
}
ngOnDestroy() {
// best practice: unsubscribe from all your observables when the component is destroyed
if(this._destroy$ && !this._destroy$.closed) {
this._destroy$.next();
this._destroy$.complete();
}
}
推荐阅读
- javascript - TypeError:访问购物车时无法读取 Commerce JS 中未定义的属性“长度”
- powerbi - 如何通过切片器中的选定值更改书签选择?可能吗?
- bigcommerce - BigCommerce API v3 未获取产品其他详细信息,例如 mpn
- javascript - 嵌入或对象标签以在没有 iframe 的情况下播放 YouTube 视频
- python - 是否有任何特定方法可以过滤 Google Drive 更改?
- git - 维护两个 git 存储库的公共文件
- javascript - 替换 Google Script Apps 中的单元格值
- azure-data-factory - 如何从 sql server 表导出到 Azure 数据工厂中的多个 csv 文件
- r - 通过顶点名称添加网络图属性
- python - Docker“运行”找不到文件