Jack
Jack

Reputation: 1

Cannot check mat-autocomplete value typeusing [displayWith]

I use mat-autocomplete and there is a feature called [displayWith] that is used to format the value and some usefulness as far as I see. In this scene, I have the following questions:

1. What is [displayWith] exactly used for? Can it be used to check the type of the text in the autocomplete even if the user enters a free text rather than selecting an option? Or clear the input if none of the option is selected?

2. I want to call a method in as shown below in order to check if the value is selected or not, but it does not work. So, can I call the method according to the type of the text?

I use similar approach to that:

<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 = (data?: any) => {
    return data ? this.sometask(data) : '';
}

sometask(data) {
    console.log(typeof(data));
}

Upvotes: 0

Views: 1180

Answers (1)

Marcin Milewicz
Marcin Milewicz

Reputation: 315

  1. If you want to display different thing that is stored in control value you need to use displayFn e.q if you provide
displayFn(data)=>`${data.name}` 

after you select item from list, you will see "Name" in autocomplete, where "Name" comes from data object {name:"Name"}. That's mean, you can display whatever you want without changing the control model.

  1. You need to provide the entire object as control value (it relates to 1. point, because now displayFn makes sense.) :)

<md-option *ngFor="let state of filteredStates | async" [value]="state">

Upvotes: 1

Related Questions