How to detect when user clears selection of mat-autocomplete?

Viewed 355

Based on value of autocomplete selection, I need to update some other form fields.

So, I added optionSelected event handler:

<mat-autocomplete (optionSelected)="onOptionSelected($event)">
    <mat-option *ngFor="let item of items"
                [value]="item">
        <span>{{item}}</span>
    </mat-option>
</mat-autocomplete>

The user should be able to clear the selection, in which case I need to reset the other fields, too.

The problem is that optionSelected is not triggered when mat-autocomplete gets emptied by the user.

How do I catch the autocomplete was cleared event?

1 Answers

What you can do is creating a FormControl for your mat-autocomplete

myControl = new FormControl();

And then associate it to your mat-autocomplete within HTML

<mat-autocomplete [formControl]="myControl" (optionSelected)="onOptionSelected($event)">
    <mat-option *ngFor="let item of items"
                [value]="item">
        <span>{{item}}</span>
    </mat-option>
</mat-autocomplete>

And finally, within your component listen for the value changes and request new data which then you will set as your options

this.myControl.valueChanges
  .pipe(
    debounceTime(500),
    distinctUntilChanged(),
    takeUntil(this.ngUnsubscribe) // optional but recommended 
  )
  .subscribe(searchPhrase => check if empty);
Related