Home > Software design >  How to check if option value was selected? Angular
How to check if option value was selected? Angular

Time:07-13

I need your help. 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. Please tell me how to check whether a certain element was selected in mat-autocomplete? Thank you very much)

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

CodePudding user response:

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>

CodePudding user response:

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