我们有两个表单字段,我们需要根据从第一个字段中选择的值来禁用或启用第二个字段。在第一个字段中,我们有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();
}
}