I encountered an issue with my autocomplete feature in Angular TypeScript where it was returning a [object Object] value

Issue with autocomplete displaying [object Object] value in Angular TypeScript

I'm having trouble pinpointing the exact problem

HTML snippet

<mat-form-field style="margin-right: 10px;">
  <input #productName matInput placeholder="Product" [(ngModel)]="objTaxInvoice.ProductName" aria-label="ProductName" [matAutocomplete]="autop" [formControl]="productCtrl">
  <mat-autocomplete #autop="matAutocomplete" (optionSelected)="onProductSelectionChanged($event)">
    <mat-option *ngFor="let product of filteredProducts | async" [value]="product">
      <span>{{product.Name}}</span>
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

Component code

 getProducts(): void {
    this.productservice.getProductList().subscribe(data => {
      this.products = data;
      this.filteredProducts = this.productCtrl.valueChanges
        .pipe(
          startWith(''),
          map(value => typeof value === 'string' ? value : value.Name),
          map(name => name ? this._filterProducts(name) : this.products.slice())
        );
    });
  }


 onProductSelectionChanged(e) {
    this.selectedProduct = e.option.value;
    this.objTaxInvoiceDetails.Product = e.option.value;
    this.objTaxInvoiceDetails.ProductName = e.option.value.Name;
    this.objTaxInvoiceDetails.Unit = e.option.value.Unit;
}

Answer №1

To properly utilize the mat-autocomplete feature, it is essential to include a display function as shown below:

displayProduct(product) {
    return product ? product.Name : undefined;
  }

In your HTML code, make sure to add the following snippet:

<mat-autocomplete #autop="matAutocomplete" (optionSelected)="onProductSelectionChanged($event)" [displayWith]="displayProduct">

For further guidance and examples, you can visit

Answer №2

Can you explain why you are utilizing both [(ngModel)] and [formControl] simultaneously in one input field?

This mixture could lead to confusion during debugging. If your intention is to stick with [formControl], then it's recommended to also include [formControlName].

I trust this information will be beneficial to you.

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

Utilize the TypeScript Compiler API to extract the Type Alias Declaration Node from a Type Reference Node

Currently, I am utilizing ts-morph library which makes use of the TS Compiler API. Here is an example of my code: export type Foo = string export const foo: Foo = 'bar' Whenever I try to find the type for the export of foo, it returns string. H ...

Is it possible to share screens via socket.io without the need for selecting a screen prompt?

I am looking to select my screen and share it on a socket.io server without any pop-up form the browser using navigator.mediaDevices.getDisplayMedia({ video: true }).then((stream: MediaStream) => { ...

Cannot see the template on the Angular Typescript component

After encountering and resolving this issue: AngularJS directive not displaying the template I decided to experiment with an Angular component and TypeScript, but unfortunately, I can't seem to make it work. The component refuses to display. This is ...

Updating webdriver-manager can sometimes result in a "spawn Unknown system error -86" message. This error

(Angular). webdriver-manager 12.1.7 is causing issues specifically on Intel-based Macs. When running e2e tests, the error message "spawn Unknown system error -86" is encountered. The bug has been addressed in webdriver-manager 12.1.8, however, I am facing ...

What is the reason for not hashing the password in this system?

My password hashing code using Argon2 is shown below: import { ForbiddenException, Injectable } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { AuthDto } from './dto'; import * as arg ...

Error: Unable to access _rawValidators property of null object

I'm currently facing an issue with formgroup and formcontrol in Angular. When I run ng serve, it's showing an error in the console. Does anyone have a solution for this? TypeError: Cannot read properties of null (reading '_rawValidators&a ...

Verifying the accuracy of a React Component in interpreting and displaying a path parameter

I have the following React/Typescript component that is functioning correctly. However, I am struggling to write a test using testing-library. My goal is to verify that it properly receives the level parameter and displays it on the page: import React from ...

What are some ways to condense this Angular/TS code for improved performance and readability?

I am in need of assistance with refactoring a method called getBaseUrl(). This method assigns a specified string value to this.baseURL based on the input serviceType. getBaseUrl(serviceType: string, network?: string) { // Method logic to determine base ...

Does Angular 4 Bundling Include the Complete Angular Library in the Bundle?

Is it possible that when running ng build --prod in CMD, Angular gathers all JavaScript files from node_modules and generates the vendor.bundle.js? To test this theory, I decided to delete certain definitions from package.json and rebuild. Surprisingly, t ...

I need to dynamically change the font color based on the data retrieved from the API

I am looking to dynamically change my font color. <div *ngIf="clientProfileModel.patientHealthScore[0].kidneyScoreStatusByColor==='Normal'" [ngStyle]="{color:'#ff5454'}" then *ngIf="clientProfileModel.pat ...

Lint found an issue: The variable 'post' has been defined but is not being utilized in the code

Within my codebase, I have included the following import: import { post } from '@loopback/rest' This is how I am utilizing it in my project: export class MyClass { @post('/example/test', {}) } Unfortunately, a lint error has been de ...

Troubleshooting ngFor usage with Object Arrays in Angular 2

I have created an Array of Objects in my Component class as shown below : deskCategories : Array<any>; this.deskCategories = [ { catLabel : 'Tools', catIcon : 'suitcase' }, { ...

Angular MatTable with Multiple Filter Options

My goal is to implement multi-column filtering, where a text input in column headers filters the content of that particular column. However, I've encountered an issue while trying to filter the client_name and module_control columns. Despite my effort ...

The filtering process of an array using the filter() method is effective, however, it does not result in any visible changes on

script.js searchVideo = (keyword) => { this.input = keyword; if(this.items.length == 0){ this.filteredItems = []; } if(!this.input){ this.filteredItems = this.items; } const args = this ...

Look for identical values within a nested array

My data consists of a nested array where each element has a property called name, which can only be either A or B. I need to compare all elements and determine if they are all either A or B. Here is an example of the input: [ { "arr": { "teach ...

Encountering a Typescript error while attempting to convert a JavaScript file to Typescript within an Express

After deciding to transition my express.js code to typescript, I have encountered an issue with my user model. Below is a simplified version of the code: //user.model.ts import { Schema, Types } from 'mongoose'; export interface User { na ...

return to the previous mat tab by using the browser's back button

Currently working on an Angular project, I am faced with the challenge of configuring the Mat Tab to close the active tab and return to the previously accessed tab when the browser's back button is clicked. How can I accomplish this without relying on ...

Can Angular Routing support distinct 'path' strings for various languages?

I've been working on an internationalized Angular app, and it's performing really well so far. However, I've noticed that I have the same route strings for different languages, which could negatively impact SEO. Is there a way to make the ...

Parsing of the module has failed due to the presence of an unexpected character '' while attempting to import a video file

Trying to create a video player in NextJS using TS. I brought in a video file from my src/assets folder and encountered an error. Error - ./src/assets/video.mp4 Module parse failed: Unexpected character '' (1:0) You may need an appropriate load ...

custom form control component combined with an issue

Trying to develop a custom MatFormFieldControl with ControlValueAccessor implementation. Starting off with a familiar scenario: password form. The objective is to design a form field that takes a single string input, but contains its own internal form fo ...