Tips for showcasing with [displayWith] in Material2's AutoComplete feature

My API returns an array and I am using Material2#AutoComplete to filter it. While it is working, I am facing an issue where I need to display a different property instead of the currently binded value in the option element.

I understand that I need to utilize displayWith, but I am not getting the expected result. The function

[displayWith]="displayFn.bind(this)"
only returns the id value. How can I access the full object and display the name instead within this function?

Additionally, I still require the id to be binded in my FormControl.

Some snippets from my code:

Component:

export class AutocompleteOverviewExample {
  stateCtrl: FormControl;
  filteredStates: any;

  states = [
    { 
      id: 1,
      name: 'Alabama'
    },
    {
      id: 2,
      name: 'North Dakota'
    },
    {
      id: 3,
      name: 'Mississippi'
    }
  ];

  constructor() {
    this.stateCtrl = new FormControl();
    this.filteredStates = this.filterStates('');
  }

  onKeyUp(event: Event): void {
    this.filteredStates = this.filterStates(event.target.value);
  }

  filterStates(val: string): Observable<any> {
    let arr: any[];
    console.log(val)
    if (val) {
      arr = this.states.filter(s => new RegExp(`^${val}`, 'gi').test(s.name));
    } else {
      arr = this.states;
    }

    // Simulates request
    return Observable.of(arr);
  }

  displayFn(value) {
    // I want to get the full object and display the name
    return value;
  }
}

Template:

<md-input-container>
  <input mdInput placeholder="State" (keyup)="onKeyUp($event)" [mdAutocomplete]="auto" [formControl]="stateCtrl">
</md-input-container>

<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn.bind(this)">
  <md-option *ngFor="let state of filteredStates | async" [value]="state.id">
    {{ state.name }}
  </md-option>
</md-autocomplete>

It is similar to this question, but the answers provided are not working correctly.

Here is the PLUNKER for reference.

Answer №1

To fully bind the entire object with the md-options directive, you can bind the option with state and return state.name in the displayFn function. This eliminates the need to bind this.

<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn">
  <md-option *ngFor="let state of filteredStates | async" [value]="state">
    {{ state.name }}
  </md-option>
</md-autocomplete>

displayFn(state) {
  return state.name;
}

Check out the demo on Plunker.


If you only want to bind state.id to the md-options directive, you will need to iterate through the states array to find the state.name based on the state.id. In this case, binding this is necessary.

<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn.bind(this)">
  <md-option *ngFor="let state of filteredStates | async" [value]="state.id">
    {{ state.name }}
  </md-option>
</md-autocomplete>

displayFn(id) {
  if (!id) return '';

  let index = this.states.findIndex(state => state.id === id);
  return this.states[index].name;
}

View the demo on Plunker.

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

Errors encountered when using Mongoose and TypeScript for operations involving $addToSet, $push, and $pull

I am encountering an issue with a function that subscribes a "userId" to a threadId as shown below: suscribeToThread: async (threadId: IThread["_id"], userId: IUser["_id"]) => { return await threadModel.updateOne( { _id: t ...

Framer Motion's "repeatType" property triggering a TypeError

Every time I try to add the repeatType property in my transition, I encounter an error related to the variants prop: index.d.ts(2779, 5): The expected type comes from property 'variants' which is declared here on type 'IntrinsicAttributes ...

Unable to display information stored in the Firebase database

I am struggling with a frustrating issue. My goal is to showcase the information stored in the Firebase database in a clear and organized manner, but I'm having trouble achieving this because it's being treated as an object. getData(){ firebas ...

Typescript issue: variable remains undefined even after being assigned a value in the constructor

In my code, I declared num1: number. constructor(){ ... this.num1 = 0; } This is all inside a class. However, when I try to log the value of this.num1 or typeof this.num1 inside a function using console.log(), it returns undefined in both cases. I ...

creating a fresh instance of a class while in a subscribe method

Although this code is functional, it briefly displays incorrect data because a blank token is instantiated before being populated in the subscribe function. Is there a way to move the instantiation into the subscribe function or provide all necessary par ...

Select the location for rendering the application within the root HTML using Single-SPA

I am strategizing to utilize the single-SPA framework alongside angular in order to construct a microfrontend architecture for a website. The current setup of the website is based on a legacy monolith structure, but we are aiming to transition it into a mi ...

Setting the date of the NgbDatePicker through code

I have implemented two NgbDatePicker components in my project: input( type="text", ngbDatepicker, #d="ngbDatepicker", [readonly]="true", formControlName='startDate', (dateSelect)='setNew ...

Master your code with Rxjs optimization

Looking at a block of code: if (this.organization) { this.orgService.updateOrganization(this.createOrganizationForm.value).subscribe(() => { this.alertify.success(`Organization ${this.organization.name} was updated`); this.dialogRef.close(true ...

Ways to resolve the error message "Type 'Promise<{}>' is missing certain properties from type 'Observable<any>'" in Angular

Check out this code snippet: const reportModules = [ { url: '', params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() } }, { url: 'application1', params: { to: for ...

Leveraging a service/provider in an Angular 2 ES6 component

I've been struggling to get a service to work properly in my component despite trying multiple iterations and exhausting all resources on Google. I've followed examples closely, and even tried using Ionic's generator to create the provider, ...

When using TypeScript, the tls.TLSSocket() function may trigger an error mentioning the absence of a "socket" parameter

Currently, I am in the process of building a basic IRC bot and using raw sockets to connect to the IRC server. Initially written in plain Javascript, I am now transitioning it to TypeScript. However, I have encountered an unusual issue when attempting to c ...

"Encountering a 500 error on Chrome and Internet Explorer while trying to sign

I am currently working on an ASP.NET Core application that handles identity management through Azure AD B2C using the ASP.Net Core OpenID Connect. The front end is developed using AngularJS 2 with TypeScript. In my Logout function, the user is redirected t ...

Consistent tree view nesting persists with each refresh

I have recently transitioned to Angular (7) from a C# background. Currently, I am using asp.net core 2.2 along with the default template that comes with a new Angular project (home, counter, fetch-data). The tree view is bound and retrieved from a controll ...

Which packages will be included once ng eject is executed?

After executing the ng eject command, I observed the following messages displayed in the console. The last line indicates that packages have been added as a result of running the command. What specific packages are included when we run ng eject? For refe ...

Encountering an issue while trying to convert a JSON object into an array of a specific class type

When I receive a JSON object from a service, I want to iterate through this object and populate an array of class types. Below is the code used to call the service: public GetMapData(): Observable<Response> { var path = 'http://my.blog.net ...

"Production environment encounters issues with react helper imports, whereas development environment has no trouble with

I have a JavaScript file named "globalHelper.js" which looks like this: exports.myMethod = (data) => { // method implementation here } exports.myOtherMethod = () => { ... } and so forth... When I want to use my Helper in other files, I import it ...

Retrieve information from an axios fetch call

Having an issue with the response interface when handling data from my server. It seems that response.data.data is empty, but response.data actually contains the data I need. Interestingly, when checking the type of the last data in response.data.data, it ...

Tips for Running Angular 2 Webpack Application on AWS EC2 Instance

I am currently running an AngularJs 2 application in development mode using the webpack-development-server My goal is to deploy this on EC2. So far, I have: - set up a new linux instance - installed node.js and npm - cloned my repository from git ...

Utilize Angular2 data binding to assign dynamic IDs

Here is the JavaScript code fragment: this.items = [ {name: 'Amsterdam1', id: '1'}, {name: 'Amsterdam2', id: '2'}, {name: 'Amsterdam3', id: '3'} ]; T ...

Tips for splitting JSON objects into individual arrays in React

I'm currently tackling a project that requires me to extract 2 JSON objects into separate arrays for use within the application. I want this process to be dynamic, as there may be varying numbers of objects inside the JSON array in the future - potent ...