I'm currently facing an issue with my Angular Autocomplete component. I am trying to trigger the (optionSelected) event within the ts file after a different event by setting the input with the updated option using
this.myControl.setValue(options[1].value)
. However, this approach does not seem to trigger the autocomplete (optionSelected) event as expected.
If you'd like to take a closer look, here is a stack blitz link:
https://stackblitz.com/edit/angular-s3gn1w-xtfxgb?embed=1&file=app/autocomplete-simple-example.ts
import { Component ,ViewChild} from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatAutocompleteTrigger, MatAutocompleteSelectedEvent } from '@angular/material'
/**
* @title Simple autocomplete
*/
@Component({
selector: 'autocomplete-simple-example',
templateUrl: 'autocomplete-simple-example.html',
styleUrls: ['autocomplete-simple-example.css'],
})
export class AutocompleteSimpleExample {
@ViewChild(MatAutocompleteTrigger) _auto: MatAutocompleteTrigger;
myControl = new FormControl();
activeOption
options: string[] = ['One', 'Two', 'Three'];
trigger?: any;
setValue() {
let options = this._auto.autocomplete.options.toArray()
this.myControl.setValue(options[1].value)
}
optionSelected($event: MatAutocompleteSelectedEvent): void {
console.log('event -->', $event);
this.trigger = $event.option.viewValue;
}
}
<form class="example-form">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" activeOption="activeOption">
<mat-option *ngFor="let option of options" [value]="option" (onSelectionChange)="optionSelected($event)">
{{option}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
<button (click)="setValue()">Set Value</button>
{{ trigger }}