Angular - 垫选项选择的值不起作用

Angular - Mat Option selected values not working

我们有两个表单字段,我们需要根据第一个字段的 selected 值禁用或启用第二个字段。在第一个字段中,我们有 5 个值,例如 'a'、'b'、'c'、'd'、'e'。用户可以从这 5 个值中 select 全部或 none。

如果用户 selects,'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();
  }
}