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?
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.
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.
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.
displayFn = value => {
// now you have access to 'this'
this.someMethod();
return 'formatted display';
}
It is because of this is not binding to the component and its binding to mat-select option
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With