Dmitry Chernyak
Dmitry Chernyak

Reputation: 305

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();
 }
}

Upvotes: 1

Views: 2253

Answers (2)

Dmitry Chernyak
Dmitry Chernyak

Reputation: 305

Typescript

isOptionSelected(event: any) {
   const selectedValue = event.option.value
   if (selectedValue) {
     this.form.controls.targetListValue.disable();
   }
}

HTML

<mat-autocomplete (optionSelected)="isOptionSelected($event)" 
                  [displayWith]="displayFn"
                  #auto="matAutocomplete"
>
    // options
</mat-autocomplete>

Upvotes: 1

MoxxiManagarm
MoxxiManagarm

Reputation: 9124

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>

Upvotes: 1

Related Questions