Clear Angular Material autocomplete after selection
I think you're close, it looks like the only missing piece is resetting the form control value in selectCategory
. This is how
we accomplished it in our own app, but it's effectively the same thing:
/** Reference to the autocomplete trigger. */
@ViewChild(MdAutocompleteTrigger)
private trigger: MdAutocompleteTrigger;
/** Form control for the input. */
searchControl = new FormControl('');
ngAfterViewInit() {
// Clear the input and emit when a selection is made
this.trigger.autocomplete.optionSelected
.map(event => event.option)
.subscribe(option => {
// This may or may not be needed, depending on your purposes
option.deselect();
// Emit the selection (so parent component can add chip)
this.selection.emit(option.value);
// Reset the value of the input
this.searchControl.setValue('');
});
}
Whenever you select a value, there will be a brief "flash" of the selected text. To avoid this,
you can use the displayWith
property to just display selected values as empty:
<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayNull">
...
</md-autocomplete>
/** Display function for selected autocomplete values. */
displayNull(value) {
return null;
}
Here my approach
in template
...
<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayNull" (optionSelected)="selectHandler($event)">
...
in component.ts
public selectHandler(event : MdAutocompleteSelectedEvent) : void
{
event.option.deselect()
this.doStuffWith(event.option.value)
}
public displayNull()
{
return null
}