How can I programmatically trigger the optionSelected event in Angular Material's autocomplete?

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

Answer №1

To trigger the optionSelected event on mat-autocomplete, you can follow this example:

html

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

typescript

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

Make sure to remove the onSelectionChange event from mat-options

Answer №2

If you want to programmatically trigger the change event, you can do so by using the autocomplete instance in your code:

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

    initiateSelectionChange(): void {
        const ac = this.myAutocomplete; // for better visibility only
        ac.optionSelected.emit({
                source: ac,
                option: ac.options.toArray().find((o) => o.selected)
        });
    }

Answer №3

Although I may be a little late to the party, my approach is centered around Angular Material versions 15 and 16. I came across this question while searching for how to highlight a selected MatOption. I wanted to share my solution in case others are facing a similar dilemma.

This addresses:

  • Selecting an option from the list
  • Angular Material 15/16 properly marking the selected option

However, it does NOT address:

  • Triggering an event that can be further processed

The method provided by @Sampgun triggers an event but doesn't always correctly mark the selection. It's unclear if this discrepancy is a bug in Angular Material or intentional behavior.

    @ViewChild(MatAutocomplete) myMatAutocomplete: MatAutocomplete;

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I remove the ID of the object data from the list?

When sending the data initially, there are no issues. However, when attempting to update, I am able to delete the root object's id but struggling to delete the ids of objects in the list. Any suggestions on what I can do? const handleSubmit = async ...

Angular ng-bootstrap modal dialog: retrieving closeResult value before proceeding with execution

I've been working on an Angular project using ng-bootstrap (currently version 5), and I've successfully implemented a modal component that can be called from multiple components with unique title and message inputs. However, I'm encounterin ...

What could be the reason for Angular 2 not recognizing this valid regex pattern?

The regular expression shown below is considered valid (check here): ^(\+27|27|0)\s?(\d{2})[-\s]?(\d{3})[-\s]?(\d{4})$ Despite its validity, Angular 2 throws the following error: EXCEPTION: Error in ./App class App - i ...

Having trouble importing the datamap library into the HTML of an Angular 2 application

I am currently in the process of developing a small Angular 2 application for educational purposes, and my intention is to incorporate datamaps for the map interface. However, there is no directive available for this library yet, so I am experimenting wit ...

The compatibility between `webpack-streams` and `@types/webpack`

I encountered an issue with my gulpfile while building it with TypeScript. Everything was working fine until I included @types/webpack-stream. Suddenly, I started getting a series of errors that looked quite ugly: node_modules/@types/webpack-stream/index.d ...

Sass encountered an issue when trying to import using the "~" symbol from the node_modules directory

I am currently developing a single-page web application using Angular 6, and I recently integrated the ngx-toast library into my project. However, I encountered an issue when trying to load the libraries by adding the following Sass code with the "~" symb ...

Troubleshooting slow performance in AngularJS ui-select

Currently, I am utilizing the UI Select control within my application (source - https://angular-ui.github.io/ui-select/). Unfortunately, it is experiencing a significant performance issue when populated with over approximately 2000 items. I have also exp ...

Navigational bar mishaps: troubleshooting the "is not a function error" in layout.tsx

I recently started learning React (Next.js) and I'm working on adding a navbar feature to my project. The goal is to have the active navlink stand out when the user is on the corresponding page. To achieve this, I created a function that updates the s ...

Tips for retrieving a server-set cookie in your Angular 2 application, and guidelines for including the same cookie in requests made by your Angular 2 application

Requirement: Our application should be able to support the same user opening our web application as a separate session. The issue is not about how to use cookies in Angular 2, but rather how the server can retrieve cookies from the HTTPServletRequest obje ...

Struggling to locate the module 'firebase-admin/app' - Tips for resolving this issue?

While working with Typescript and firebase-admin for firebase cloud functions, I encountered the error message "Cannot find module 'firebase-admin/app'" when compiling the code with TS. Tried solutions: Reinstalling Dependency Deleting node_modu ...

How to extract Response body as either plain text or XML in an AngularJS 2 HTTP GET call

I have a challenge with making a get request to the server that returns XML: let responseText = ""; this.http.get('http://example.com', {headers : headers}) .map((res:Response) => res.text()).subscribe(data => responseText = data); H ...

Validation for Angular nb-step and nb-select components

Looking at this code snippet: <nb-stepper #stepper orientation="horizontal"> <!-- **************** STEP N1 **************** --> <nb-step [label]="labelOne"> <ng-template #labelOne>Area</ng-temp ...

I can't find my unit test in the Test Explorer

I'm currently working on configuring a unit test in Typescript using tsUnit. To ensure that everything is set up correctly, I've created a simple test. However, whenever I try to run all tests in Test Explorer, no results are displayed! It appear ...

What are the steps for integrating Socket.IO into NUXT 3?

I am in search of a solution to integrate Socket.IO with my Nuxt 3 application. My requirement is for the Nuxt app and the Socket.IO server to operate on the same port, and for the Socket.IO server to automatically initiate as soon as the Nuxt app is ready ...

Retrieving information from an http request within a for loop in an Angular 2+ application

I have a scenario where I need to call my http request inside a for loop in order to process 1000 items at a time. Here's the code snippet that implements this logic: getData(IDs: string[]): Observable<any> { // IDs is a large array of strin ...

Angular files not being delivered by Express server

I have finished compiling my Angular front-end and placed it in the public folder of the Node.js back-end, which is now accessible from the browser: app.use(express.static('public')); I've also configured Express to serve the content: app ...

Using Typescript: Defining a property's type based on the value of another property in the same object

I'm dealing with a TypeScript interface that consists of two properties (type:string and args:object). The contents of the args property may vary based on the value of the type. I'm looking for the correct type definition to specify for the args ...

Manage scss styles consistently across Angular projects with this Angular library designed to

In an effort to streamline my development process, I am looking to consolidate my commonly used styles that are defined in my Angular library. My goal is to easily leverage mixins, functions, variables, and more from my library in future projects. Previou ...

Errors detected while attempting to install dependencies using pnpm: modules unspecified

I recently decided to experiment with using pnpm instead of npm for my new projects, but I've encountered an issue. Let's take my nuxt project as an example. First, I set up my project using the command: pnpx nuxi init my-project Then, I insta ...

Unfortunately, despite attempting to kill all processes linked to port 4200, it seems that it is still in use

Getting angular up and running on my Mac OS X 10.11.3 El Capitan has been quite a challenge. After installing nodeJS and npm, I used npm to install angular-cli. To create a new app, I executed the command sudo ng new first-app Then, I navigated into the ...