angulartypescriptmat-autocompletemat-option

How to check if option value was selected? Angular


I have a template, with mat-autocomplete, in which I search for elements and I have option elements - each individual element. My goal is to write logic: if I have an element selected, my input should be disabled. How can I check whether a certain element was selected in mat-autocomplete?

HTML

<input [matAutocomplete]="auto" matInput formControlName="targetListValue">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
   <mat-option *ngFor="let targetItem of filteredTargetListOptions" [value]="targetItem">
     {{targetItem.value}}
   </mat-option>
</mat-autocomplete>

Typescript

ifSelectedItem() {
 if (// if option has been selected) {
   this.form.controls.targetListValue.disable();
 }
}

Solution

  • According to the docs (https://material.angular.io/components/autocomplete/api) MatAutoComplete has a optionSelected output. Hence I'd try the following:

    <input [matAutocomplete]="auto" matInput formControlName="targetListValue">
    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" (optionSelected)="ifSelectedItem()">
       <mat-option *ngFor="let targetItem of filteredTargetListOptions" [value]="targetItem">
         {{targetItem.value}}
       </mat-option>
    </mat-autocomplete>