While the solution presented by André Dias works when you have a strict selection choice, it won't do if you need to add a substring of one in the selection (think of "java" when you have only "javascript" in autocomplete). For this also to work you can use the optionActivated
event with a global variable (this does not solve completely the problem, you still have the issue if you select with the mouse). Below an example.
The html part:
<mat-autocomplete
#auto="matAutocomplete"
(optionActivated)="optionActivated($event)"
(optionSelected)="selectedTag($event)">
<mat-option *ngFor="let tag of filteredTags | async" [value]="tag">
{{ tag }}
</mat-option>
</mat-autocomplete>
The component part:
autocompleteTagsOptionActivated = false;
optionActivated($event: MatAutocompleteActivatedEvent) {
if ($event.option) {
this.autocompleteTagsOptionActivated = true;
}
}
and then check the boolean variable and set it to false when actually added from keyboard selection:
addTag(event: MatChipInputEvent): void {
const input = event.input;
const value = event.value;
if ((value || '').trim() && !this.autocompleteTagsOptionActivated) {
this.formArrayTags.push(this.formBuilder.control(value.trim().toLowerCase()));
}
// Reset the input value
if (input) {
input.value = '';
}
this.tagsControl.setValue(null);
this.formArrayTags.markAsDirty();
}
selectedTag(event: MatAutocompleteSelectedEvent): void {
this.formArrayTags.push(this.formBuilder.control(event.option.viewValue));
this.tagInput.nativeElement.value = '';
this.tagsControl.setValue(null);
this.autocompleteTagsOptionActivated = false;
}