How to trigger optionSelected Angular Material autocomplete programmatically?

Discussão em 'Angular' iniciado por Crystal, Fevereiro 23, 2025.

  1. Crystal

    Crystal Guest

    I have an Angular Autocomplete component that I'm trying to trigger the (optionSelected) event within the ts file after a different event. I am setting the input with the updated option with this.myControl.setValue(options[1].value) however, that does not trigger the autocomplete (optionSelected) event.

    Here is a stack blitz:

    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 }}

    Continue reading...

Compartilhe esta Página