The functionality of Angular's mat-autocomplete is hindered when it comes to utilizing options generated by a function

I decided to enhance the autocomplete feature on my project by taking an example from the Material official website. Instead of having the options stored in a variable within the component class, I created a function to retrieve the options. Although the options display correctly, I encountered an issue where I am unable to select any value. Clicking on the drop-down menu does not result in selecting a value.

Check out a sample project showcasing this issue on StackBlitz.

<mat-autocomplete #auto="matAutocomplete">
  <mat-option *ngFor="let option of options()" [value]="option">
    {{option.value}}
  </mat-option>
</mat-autocomplete>

export class AutocompleteSimpleExample {
  myControl = new FormControl();
  options(): KeyValue[] {
    return [{ key: "1", value: "One" }];
  }
}
interface KeyValue {
  key: string;
  value: string;
}

Answer №1

When using ngFor with data returned by a function as the data source, clicking on mat-option triggers a change detection process. This causes ngFor to retrieve a new array and generate new mat-options, which may lead to issues with selection. To prevent this, you can utilize the trackBy function.

component.html

 <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of options();trackBy:trackByIdentity" [value]="option">
        {{option.value}}
      </mat-option>
    </mat-autocomplete>
    <!-- #enddocregion mat-autocomplete -->
  </mat-form-field>

component.ts

trackByIdentity:TrackByFunction<{key:string,value:string}> = (index: number, item: any) => item.key;

See Working Example Here

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

Alert: Prop type validation error: The `component` prop provided to `ForwardRef(Link)` is invalid

We are facing an issue with our NextJS app where it works fine in production, and locally it renders correctly. However, we are encountering some unsightly warnings that we are trying to suppress. client.js:1 Warning: Failed prop type: Invalid prop `compon ...

Discover a component-sharing feature within Angular 2

Currently, I have a page that displays all records in a table with pagination at the bottom. I believe this pagination feature should be an independent component so it can be reused in various management panels such as UserManagement and PostManagement. T ...

Interface constructor concept

Trying to figure out how to dynamically add different types of components to a game object in TypeScript. After consulting the TypeScript documentation on interfaces, I discovered a unique approach for dealing with constructors in interfaces, which led me ...

Change the variable value within the service simultaneously from various components

There is a service called DisplaysService that contains a variable called moneys. Whenever I make a purchase using the buy button on the buy component, I update the value of this variable in the service from the component. However, the updated value does n ...

Encountering issues during the installation of the Angular/CLI software

Whenever I execute the command below: npm install -g @angular/cli I encounter this error message: C:\Users\AA>npm install -g @angular/cli npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80f ...

Exploring the functionality of the Angular 7 date pipe in a more dynamic approach by incorporating it within a template literal using backticks, specifically

I have a value called changes.lastUpdatedTime.currentValue which is set to 1540460704884. I am looking to format this value using a pipe for date formatting. For example, I want to achieve something like this: {{lastUpdatedTime | date:'short'}} ...

Are you interested in verifying the user's login status on the website using a Chrome extension?

My latest project involves creating a chrome extension using angular for a PHP website. Currently, the extension is working smoothly. It features a button that I would like to have the ability to enable or disable based on whether the user is logged in o ...

The mermaidAPI.initialize function in Angular does not support the maxTextSize option

I'm currently encountering an issue while attempting to utilize mermaidAPI.initialize in an Angular environment. ngOnInit(): void { this.windowHeight = window.innerHeight; mermaidAPI.initialize({ maxTextSize: 1000000, logLevel: & ...

Why is it important to use linting for JavaScript and TypeScript applications?

Despite searching extensively on Stack Overflow, I have yet to find a comprehensive answer regarding the benefits of linting applications in Typescript and Javascript. Any insights or resources would be greatly appreciated. Linting has become second natur ...

Unable to determine the data type of the property within the table object

Is it feasible to retrieve the type of object property when that object is nested within a table structure? Take a look at this playground. function table<ROW extends object, K extends Extract<keyof ROW, string>>({ columns, data, }: { col ...

The build process encounters an issue with initializing Sentry's Vuejs (with Typescript) Integration

While attempting to build my (vue-cli-3 based) Vuejs project using gitlab-runner on my local machine, an error occurs: 98% after emitting CopyPlugin ERROR Failed to compile with 1 errors ... Property 'util' is missing in type 'VueConstruct ...

The type 'Observable<Subscription>' does not match the type 'Observable<MyData>' in RxJS Angular

When utilizing Angular, I've developed a service that retrieves data from multiple sources and combines it with the original service. Below is the code snippet: searchData(): Observable<MyData> { const url = `${this.context}/search`; ret ...

What is the process for connecting custom transformers to a compiler host?

My custom TypeScript watcher is set up like this: const compilerHost = typescript.createWatchCompilerHost(config.fileNames, config.options, typescript.sys, undefined, reportDiagnostic) typescript.createWatchProgram(compilerHost) I am trying to integrate ...

``There seems to be an issue with the Angular Material Table dataSource, as it is not binding correctly or updating

When examining the served page: <table _ngcontent-c6="" class="mat-elevation-z8 mat-table" fxfill="" mat-table="" matsort="" role="grid" ng-reflect-data-source="[object Object]"> In View: table matSort fxfill mat-table [dataSource]="dataSou ...

Experiencing problems with npm installation while trying to compile Angular2 source code

I am trying to compile angular2 source code on my Windows 8.1 x64 development machine. The versions of Node and Npm I have are as follows: Node version 5.1.0 Npm version 3.3.12 1) Successfully cloned the repository 2) Executed bower install command - S ...

Angular material table featuring custom row design

My team is working with a large table that is sorted by date, and we are looking to add some guidance rows to help users navigate through the data more easily. The desired structure of the table is as follows: |_Header1_|_Header2_| | 25/11/2018 | ...

Transforming TypeScript declaration files into Kotlin syntax

Has there been any progress on converting d.ts files to Kotlin? I came across a post mentioning that Kotlin developers were working on a converter, but I am unsure about the current status. I also found this project, which seems to be using an outdated c ...

Using a configuration file with the JavaScriptServices React-Redux template

I have come across this question many times on different platforms, but I haven't been able to make it work for me. The issue is that I am using an API within a React component (with TypeScript 2.4.1 and webpack 2.5.1): .... fetch("some/url/api/", me ...

Preserve data even after refreshing the browser in Angular

Is there a reliable method to preserve my data after refreshing my browser? I've experimented with rxjs behavior subject, but it hasn't worked for me. I prefer not to use local/session storage due to security concerns and best practices, especia ...

Angular 2 - resolving the access control allow origin header issue

My project utilizes Spring on the back-end and Angular2 on the front-end. In the webapp folder of my Spring project, there is a JSON file that I am attempting to access from Angular. I can successfully access the file by directly typing "http://localhost: ...