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

Issue with Angular Route Guard - Incorrect redirection to login page

I'm encountering an issue with my Angular app where even after the JWT token has expired, I am still able to navigate within the application without any API data being accessible. I've double-checked my setup and it seems right, but for some reas ...

Tips for determining the overall percentage breakdown of 100% based on the individual denominator for every column within angular 8

In my code, I have a simple function that calculates the sum of numbers and strings in columns within a table. The sum calculation itself works fine and provides accurate results. However, the problem arises when I attempt to divide the total sum of each c ...

Merging Two JSON Objects into a Single Object Using Angular 4-6

Two JSONs are available: The first one (with a length of 200): {date_end: "2099-12-31", id: "2341"} {date_end: "2099-12-31" id: "2342"} ... The second one (length 200): {type: "free", discount:"none", warranty: "yes"} {type: "free", discount:"none", ...

When using Router.push() in next.js, the error TypeError: products.map is not a function may arise

Currently, I am implementing redux saga in my project. Here is how the state looks: const productList = useSelector((state: RootState) => state.productList); const { loading, error, products, page, pages } = productList; In the useEffect hook, I dispa ...

There is only a singular font awesome icon that appears properly based on the conditions set by [ngClass

I'm currently developing a user profile feature that allows users to submit links to their social media accounts. Each account is represented by a clickable icon, and the selection of which icon to display is based on various conditions within [ngClas ...

Changing an Angular template.html into a PDF document within an Angular 2 application can be achieved by utilizing

Exploring Angular 2 and looking for a way to export my HTML component in Angular 2 to PDF using jspdf. I want to convert dynamically generated tabular HTML into a PDF using jspdf. Below is a snippet of sample code along with a Plunker link: import {Comp ...

Is there a feature similar to notifyWhenNoOutstandingRequests in Angular 2?

In my experience, test frameworks like Arquillian have utilized this method to determine when the DOM is ready for inspection with Angular 1. I am curious if there is a similar approach for accomplishing this in Angular 2? ...

"Angular 4 is requesting a required get parameter that is currently missing

After running my code, I encountered the following console log error: "'Missing required 'page' parameter". I attempted to set this as a parameter in my get request, and it seemed successful because I was able to view the params as an array ...

Tips for overlaying a webpage with several Angular components using an element for disabling user interactions

I currently have an asp.net core Angular SPA that is structured with a header menu and footer components always visible while the middle section serves as the main "page" - comprised of another angular component. What I am looking to achieve is ...

Support for BigInt is not available in TypeScript version 3.5.*

It seems that TypeScript has supported BigInt since version 3.2, and my project is using TypeScript 3.5. Despite not explicitly declaring any variables as BigInt, I recently integrated a package called BufferUtility from https://github.com/Pharuxtan/Buffer ...

The menu's mouseover event is activated when hovering over the inner element

Whenever a user hovers over a specific element, a menu appears. This menu remains visible only as long as the user is hovering over it. However, the issue arises when there are elements within the menu itself, causing the menu to hide when the user hovers ...

The Angular filter feature operates on individual columns instead of filtering all columns simultaneously

Introduction I am currently working on implementing a feature in my Angular application where the column filter continuously updates the results based on the selected filters. The issue I'm facing is that when I select a filter in one column, it corr ...

Angular 6: Utilizing async/await to access and manipulate specific variables within the application

Within my Angular 6 application, I am facing an issue with a variable named "permittedPefs" that is assigned a value after an asynchronous HTTP call. @Injectable() export class FeaturesLoadPermissionsService { permittedPefs = []; constructor() { ...

Update md-progress-linear without causing a $digest cycle

The example showcasing the usage of md-progress-linear provides the following code snippet; <md-progress-linear md-mode="determinate" value="{{vm.determinateValue}}"> </md-progress-linear> It then updates the progress as follows; $interval( ...

Issue: Unable to resolve all parameters for LoginComponent while implementing Nebular OAuth2Description: An error has occurred when attempting to

I have been attempting to utilize nebular oauth in my login component, following the documentation closely. The only difference is that I am extending the nebular login component. However, when implementing this code, I encounter an error. export class Lo ...

Learn how to restrict input to only specific characters in an input box using Angular2 and validations

Is it possible to restrict user input in an input box to only specific characters such as '7' and '8'? I tried adding validations with attributes like type="number", min="7" and max="8", but even then other keys can be inserted before v ...

The slides in Swiperjs are having trouble moving smoothly

I am experiencing some challenges with swiperjs where the slides are not snapping to the next slide and I am unable to fetch the active index from them. Below is a snippet of my code where I am using typescript, swiperjs version 6.84, and the Ionic frame ...

The 'target' property is not found on the type 'KeyboardEventHandler<HTMLInputElement>'

My Visual Studio Code is giving me an error in my onKeyUp function when I try to access the input target and retrieve its value. import React from 'react'; import styles from './styles.module.scss'; export function Step3() { ...

"Error: imports are undefined" in the template for HTML5 boilerplate

After setting up an HTML5 Boilerplate project in WebStorm, I navigate to the localhost:8080/myproject/src URL to run it. Within the src folder, there is a js directory structured like this: libraries models place.model.ts place.model.js addr ...

Tips for solving the error "Angular CLI version 7.0.3 cannot install node-sass"

Every time I attempt to run npm start, an error message stating that it cannot find the module node-sass appears. Then, when I try running npm install node-sass --save, a series of errors pop up. https://i.stack.imgur.com/2I7DU.png ...