首页 > 解决方案 > 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>

标签: angulartypescriptangular-materialangular7

解决方案


在您的打字稿代码上(假设您的 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();
  }
}

推荐阅读