When typing some text into the input and selecting an option from the autocomplete by hiting enter, it saves as chips both of the strings. Image here
However, this doesn
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:
{{ tag }}
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;
}