When the component is initialized, the mat-autocomplete input element displays a [object object]

     HTML:
<form [formGroup]="basicForm">
    <section>
    <mat-form-field>
                <mat-label>Select Country*</mat-label>
                <input matInput type="text" maxlength="20" formControlName="country [matAutocomplete]="auto">
                <mat-autocomplete #auto="matAutocomplete" [displayWith]="countryDisplayWith">
                    <mat-option *ngFor="let country of filteredCountryAutoCompleteOptions | async [value]="country">
                        {{country}}</mat-option>
                </mat-autocomplete>
            </mat-form-field>
</section>
</form>

/////////////////////////////////////////////////

TS:

filteredCountry: string[] = ['abc', 'def', 'ghi'];

this.basicForm = new FormGroup({
      country: new FormControl({ value: '' }, Validators.required) });

filteredCountryAutoCompleteOptions: Observable<string[]> | undefined;
  countryDynamicFilter() {
    this.filteredCountryAutoCompleteOptions = this.basicForm.controls.country.valueChanges.pipe(
      startWith(''),
      map((value) => this._filter(value))
    );
  }
  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();
    return this.filteredCountry.filter(
      (option) =>
        option.toLowerCase().includes(filterValue)
    );
  }
  countryDisplayWith(op: any) {
    return op ? op: '';
  }

I am experiencing an issue where I see [Object Object] initially in the Input Box as a value, although the autocomplete functionality works correctly.

I suspect that this problem is related to the [displayWith] attribute. Any assistance in resolving this would be greatly appreciated.

Answer №1

.component.html

Make a change to the <mat-option> element so that it displays a string like {{country.name}} instead of just {{country}} since country is an object.

<mat-autocomplete #auto="matAutocomplete" [displayWith]="countryDisplayWith">
  <mat-option *ngFor="let country of filteredCountryAutoCompleteOptions | async" [value]="country">
    {{ country.name }}
  </mat-option>
</mat-autocomplete>

Also, update the function for [displayWith] to show the country.name rather than just country.

.component.ts

countryDisplayWith(op: any) {
  return op ? op.name : '';
}

References

Setting separate control and display values

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

I am struggling to grasp the syntax for defining xpath in typescript language

Display the text of the first TextView element within a nested hierarchy of Android widgets using the xpath provided. ...

Prevent updating components when modifying state variables

Introduction I've developed a React component that consists of two nested components. One is a chart (created with react-charts) and the other is a basic input field. Initially, I have set the input field to be hidden, but it becomes visible when the ...

I am experiencing an issue with my Angular application where it appears blank on gh-pages and is unable to load JavaScript from Travis

After uploading an Angular app with Travis on Github pages using the gh-pages branch, I'm encountering a frustrating issue. The page is blank and there are several error messages in the console: Failed to load resource: https://hdz.github.io/runtime.j ...

Is there a way to inject a parent component into a shared directive without explicitly stating the component type?

Is there a way to specify my directive so that it can be utilized in all components? my directive.ts : import { Parent } from '../../_common/Parent'; declare var jQuery: any; @Directive({ selector: '[icheck]' }) export class Ichec ...

Error code 1 in Ionic V5 Capacitor - cordova-plugin-media indicates a problem with media playback

Despite installing the plugin and ensuring all necessary permissions are set, I am still encountering error code 1 with the media plugin. I have also included <application android:requestLegacyExternalStorage="true" /> in <edit-config&g ...

How can PrimeNG PIE chart values be displayed by default instead of only on hover over the slice?

front end <td> <div class="p-col-8 ui-toolbar-group-right"> <button pButton type="button" icon="pi pi-search" (click)="populate_charts()"></button> </div> </td> TS-File ...

Adding a component dynamically to a div in Angular 5

Can anyone help me with this issue? I have successfully managed to dynamically append an element, but it is not getting compiled. I have looked at several tutorials like this one However, these tutorials do not exactly meet my requirements. They often us ...

Splitting Angular modules into separate projects with identical configurations

My Angular project currently consists of approximately 20 different modules. Whenever there is a code change in one module, the entire project needs to be deployed. I am considering breaking down my modules into separate projects for individual deployment. ...

Set the values retrieved from the http get response as variables in an Angular application

Lately, I've been working on a settings application with slide toggles. Currently, I have set up local storage to store the toggle state. However, I now want to update the toggle status based on the server response. The goal is to toggle buttons accor ...

Sharing the port of a local Node.js HTTP server (which is being executed in an Electron environment) with an Angular

Running a RESTful node JS Http server on localhost within an electron app, listening on port 0 to get a random free port. How can I access this randomly assigned port in my Angular code to determine the URL for XHTTP requests? Nodejs restapi server runnin ...

Passing RxJs pipes as a parameter

Is there a way to pass pipes as parameters? For example: var mypipes = [ pipeA(() => { alert("a"); }), pipeB(() => { alert("b"); }) ...

Tips for invoking an Android function from an AngularJS directive?

I am facing an issue with my HTML that uses an AngularJS directive. This HTML file is being used in an Android WebView, and I want to be able to call an Android method from this directive (Learn how to call Android method from JS here). Below is the code ...

Angular2 - Utilizing Promises within a conditional block

I'm currently facing an issue where I need to await a response from my server in order to determine if an email is already taken or not. However, I am struggling to achieve this synchronously. TypeScript is indicating that the function isCorrectEmail( ...

fresh perspective on the syncfusion schedule angular component

In customizing the Schedule component in Angular, I am interested in finding out if there is a way to specify the start time and end time for each day. I would like to set the start and end times for each individual day rather than having the same times a ...

The issue of assigning a file as a prop in React TypeScript: ("True" type cannot be assigned to "ChangeEventHandler<HTMLInputElement>")

I'm currently developing an application using reactjs My goal is to implement a feature that allows file uploads passed as a prop from a child component to a parent component Child Component const RegisterIndividual: React.FC< { upload_id_card: R ...

Creating a custom validation for browsing HTML files in Angular using the Form Builder

Currently, I am using reactive form validation to validate a file upload control. I have implemented a change directive to manage its validation. <label class="btn btn-primary btn-file"> Browse <input type="file" (change)="fileChanged($event)" ...

Obtain headers from an Excel file uploaded using the XLSX format in Angular

Is there a way to extract the first row containing name, email, and mobile as an array from an uploaded excel file? I am currently utilizing XLSX for this purpose. While I am able to retrieve the entire dataset into an array, my main goal is to only ex ...

Leverage the power of Maps in TypeScript by incorporating additional fields

There is a slight issue I am facing. The data I have looks like this: ["1112234", "S1044N", "A1041DS"] I am interested in using Map to generate a new array, but I wish to include additional properties for each field. Here is ...

Sometimes the downloaded xlsx file may become corrupted

Currently, I am working on developing a project using Angular4 with Typescript. One of the tasks involved creating a blob utilizing the XLSX-populate library. Below is an example showing the code snippet for generating a valid xlsx object: var url = wind ...

Testing Angular2 / TypeScript HTTPService without Mocking: A Guide

import {Injectable} from '@angular/core'; import {Http} from '@angular/http'; @Injectable() export class HttpService { result: any; constructor(private http:Http) { } public postRequest(){ return this.http.get('h ...