Crystal
Crystal

Reputation: 1505

How to trigger optionSelected Angular Material autocomplete programmatically?

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

Upvotes: 6

Views: 14996

Answers (4)

bresleveloper
bresleveloper

Reputation: 6066

in my case only MatAutocompleteTrigger helped me

@ViewChild('qauto') qauto!: MatAutocomplete;
@ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger;
        setTimeout(() => {
          let o = this.qauto.options.first; // or use find
          trigger.writeValue(o.value)
        }, 150);

Upvotes: 0

LeO
LeO

Reputation: 5270

Although a little bit late to the party - nevertheless. My approach is based on Angular Material 15/16. I found the question on search of how to mark a selected an MatOption. Therefore I thought my solution might fit in - in case others are looking for similar solutions.

What it solves:

  • select an option in the option list
  • Angular Material 15/16 marks this option

What it does NOT solve:

  • Trigger an event which can be processed further

The approach from @Sampgun triggers an event but does not necessarily mark the selection. Don't know if this is a bug in Material or works as designed :-|

    @ViewChild(MatAutocomplete) myMatAutocomplete: MatAutocomplete;

    const selMatOption = this.myMatAutocomplete.options.toArray()
                             .find((o) => o.value === item2BeFount);
    selMatOption?.select();

Upvotes: 2

Sampgun
Sampgun

Reputation: 3002

You can trigger the change event programmatically, using the autocomplete instance:

    <mat-autocomplete #myAutoComplete="matAutocomplete" 
                      (optionSelected)="onSelectionChanged($event)">
    @ViewChild(MatAutocomplete) myAutocomplete: MatAutocomplete;

    triggerSelectionChanged(): void {
        const ac = this.myAutocomplete; // useless, just for better display here :)
        ac.optionSelected.emit({
                source: ac,
                option: ac.options.toArray().find((o) => o.selected)
        });
    }

Upvotes: 1

JLazar0
JLazar0

Reputation: 1292

Use the optionSelected event on mat-autocomplete like this:

html

<mat-autocomplete #autoCompleteUser="matAutocomplete" (optionSelected)="onSelectionChanged($event)">

typescript

onSelectionChanged(event: MatAutocompleteSelectedEvent) {
    console.log(event.option.value);
    [...]
}

Remove the onSelectionChange event from mat-options

Upvotes: 1

Related Questions