Disable input field after select the value in mat autocomplete in angular?

2.4k Views Asked by At

Hi every i want to disable the input field after selected the value in drop down, and i want to reset the selected value using of reset button.

For reference Stackblitz : https://stackblitz.com/edit/mat-autocomplete-1uelcd?file=app%2Fautocomplete-display-example.html

For example:- If we selected any value in the input field then filed should be disabled after clicks the reset button it should enabled to select the value please check and help us.

Html:

    <div class="example-form">
      
      <form>
        <mat-form-field class="example-full-width">
          <input type="text" placeholder="Assignee" aria-label="Assignee" matInput [formControl]="myControl" [matAutocomplete]="auto2">
          <mat-autocomplete #auto2="matAutocomplete" [displayWith]="displayFn">
            <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
              {{ option.name }}
            </mat-option>
          </mat-autocomplete>
        </mat-form-field>
         <button  mat-raised-button (click)="onResetSelection()" color="primary">Reset Selection</button>
      </form>
     
    </div>

Reset:


onResetSelection() {
    this.filteredOptions = [];
}

Disable:

[disabled]="filteredOptions =='option'"
1

There are 1 best solutions below

3
On

You can do that with below approach

Add on select event to disable form control and while doing reset event just clear the form control.

In View :

  <mat-autocomplete #auto2="matAutocomplete" (optionSelected)="onSelectionChanged($event)" [displayWith]="displayFn">
        <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
           {{ option.name }}
        </mat-option>
   </mat-autocomplete>

In Template :

  ...

  onSelectionChanged(event: any) {
     this.formGroupName.controls['myControl'].disable();
  }

  onResetSelection() {
    // you can enable the control with below line
    this.formGroupName.controls['myControl'].enable();
    this.formGroupName.controls['myControl'].setValue('');
  }

  ...

Happy Coding.. :)