Search code examples
angulartypescriptangular-materialangular7

Angular - Mat Option selected values not working


We have two form fields and we need to disable or enable the second field based on selected value from first field. In first field, we are having 5 values like 'a','b','c','d','e'. User can select all or none from these 5 values.

If user selects, 'C' we need to enable second form field otherwise it should be disabled.

Can someone please help me to write this logic.

                   <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>

Solution

  • On your typescript code (supposing your formGroup is called _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();
      }
    }