I'm building a form where I use the Angular Material Autocomplete module. I load the options from a server and I filter them with an input. It works great, and now I wanted to add a "clear" icon to clear the field if needed.
The clear option clears the field, but it doesn't show the autocomplete options again. It shows them when I manually delete the input contents with backspace but not with the icon.
To "clear" the field I use this code:
clear(control: string): void {
this.form.get(control).setValue('');
}
And I call it from a mat-icon component:
<mat-form-field>
<input matInput type="text" ... >
<mat-icon matSuffix (click)="clear(fieldName)" ...>
clear</mat-icon>
</mat-form-field>
<mat-autocomplete> ... </mat-autocomplete>
Where fieldName (string) is the name of the control I want to clear.
And this is how I filter the autocomplete options:
this.filter = this.form.get(field).valueChanges.pipe(
startWith(''), // Don't even know what this does...
map(value => this.options.filter(option => option.name.toLowerCase().includes(value.toString().toLowerCase())))
);
I suspect that maybe there's an error with the setValue('') inside the clear() method. Or maybe its the filter method that I'm using.
Here's the full example in StackBlitz:
https://stackblitz.com/edit/angular-autocomplete-clear9zzmw2