1
votes

I have a simple input with autocomplete

<input [matAutocomplete]="auto" (focusout)="save()">
<mat-autocomplete #auto="matAutocomplete">
   <mat-option *ngFor="let number of numbers" [value]="number">
     {{number}}
   </mat-option>
</mat-autocomplete>

I want to save the input value when the user is no longer using the input field

The issue is when i am clicking on a autocomplete option focusout function of input field is called.

What are my options to save input value which checks both autocomplete and input field status

Thankyou

2
You want to save it where? - Nicholas K
Hey Nicholas i am calling a service which saves the value in the Database, The actual implementation is very big but i found out the root cause of my problem to be this - Nihal Reddy
Why would you want to save on focusout? Users may interact several times before being 'done'. - G. Tranter

2 Answers

1
votes

If you ONLY want to handle the clicking on autocomplete option you should use (click) on that option to handle it.

<input [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
   <mat-option (click)="save(number)" *ngFor="let number of numbers" [value]="number">
     {{number}}
   </mat-option>
</mat-autocomplete>

However, if you want to do it with focus, this will work:

<input #myInput (focusout)="save(myInput.value)" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
   <mat-option *ngFor="let number of numbers" [value]="number">
     {{number}}
   </mat-option>
</mat-autocomplete>

Stackblitz

0
votes

Yes, there's a way we can do that,

<input [matAutocomplete]="auto" matInput (focusout)="onFocusOut()" [formControl]="autoInput">
<mat-autocomplete #auto="matAutocomplete">
  <mat-option *ngFor="let number of numbers" [value]="number">
      {{number}}
  </mat-option>
</mat-autocomplete>

here is the code, I have added a formControl to bind autoComplete value to a variable. And here is the way, we can access the matInput value after matInput is focused out, then we can perform some operations like autoSelect a value or filter options, etc. to manipulate autocomplete input value.

// since focusout will be called after optionSelected event called of 
// matAutoComplete, we are adding timeOut to delay focusOut operations
// and so we will have the true value of autoInput

onFocusOut() {
  setTimeout(() => {
    let input = this.autoInput.value;
    // filtering matching values from options and 
    // selecting first matched or set the default value
    let matchingOption = this._filter(input)[0] || 'DEFAULT VALUE';
    // now set the best matching option 
    // or let's call it autoSelects best match option for an user
    this.autoInput.setValue(matchingOption);
  }, 300);
}


   

This way, we will be able to manipulate autocomplete input value on matInput focused out.

Thank you.