Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding 'this' in Angular Material Autocomplete displayWith using Angular 5

I was trying to use the Material Angular autocomplete and I came across the displayWith function which can be apparently used to be the output that is displayed on selection. I wanted to call a custom function within the display function like

displayFn(id) {
 return this.getValue(id)
}
getValue(id) {
 /**return some string
}

For the autocomplete

<mat-autocomplete #autoOutlet="matAutocomplete" [displayWith]="displayFn">
  <mat-option *ngFor="let option of outletFilterOptions | async [value]="option.outletId">
   {{ option.outletName }}
  </mat-option>
</mat-autocomplete>

As you see I am using the id as the model instead of the entire object.

When the display function returned an error that this.getValue is undefined I searched Stack Overflow for a solution and was suggested that I use something like [displayWith]="displayFn.bind(this)".

But unfortunately, that isn't working for me either. I am using Angular material 5.1.0.

Is there something I am missing?

like image 252
Sriram Jayaraman Avatar asked Apr 20 '18 10:04

Sriram Jayaraman


People also ask

How do I use angular material autocomplete?

Simple autocompleteStart by creating the autocomplete panel and the options displayed inside it. Each option should be defined by a mat-option tag. Set each option's value property to whatever you'd like the value of the text input to be when that option is selected.

What is Displaywith in angular?

displayWith : ((value: any) => string) | null. Function that maps an option's control value to its display value in the trigger. @Input().... Read more > Angular Autocomplete Displaywith With Code Examples.

How do you clear mat autocomplete when no option is selected from autocomplete dropdown?

Answers 1 : of How to clear mat- autocomplete when no option is selected from autocomplete dropdown. You can remove the formControl-binding from your input and when you select an option you set that id to your form.


2 Answers

displayFn = value => {
  // now you have access to 'this' 
  this.someMethod();
  return 'formatted display';
}
like image 182
IonutAnin Avatar answered Sep 21 '22 23:09

IonutAnin


It is because of this is not binding to the component and its binding to mat-select option

enter image description hereenter image description here

NOw for using component's function, you have to use arrow function, the preferable method or pass this from the HTML function

I will use the arrow function to use the component's function

Without arrow function

displayFn(data: any) {
    return data.Id?this.sometask(data):''
}

With arrow function

displayFn = (data: any) => {
    return data.Id?this.sometask(data):''
}

This work in my scenario and it worked in your scenario too.

like image 26
VIKAS KOHLI Avatar answered Sep 23 '22 23:09

VIKAS KOHLI