I have Angular 8
mat-autocomplete
with [displayWith]="getDropdownView"
where
getDropdownView(option) {
console.log("getDropdownView(): option:", option);
return "abc"; // FOR TEST
// return option.value;
}
For one page this works ok, but for another one this shows [Object Object]
. There is such HTML code:
<input matInput placeholder="Начните вводить..." [matAutocomplete]="auto" [id]="field.field"
[value]="getDropdownValue(field.field)"
(input)="loadDropdownData($event.target.value, field.field)">
<mat-autocomplete #auto="matAutocomplete" autoActiveFirstOption
(optionSelected)="onDropdownSelected($event.option.value, field.field)"
[displayWith]="getDropdownView">
<mat-option *ngIf="dropdownIsLoading[field.field]" class="is-loading">
<mat-spinner diameter="50"></mat-spinner>
</mat-option>
<mat-option *ngFor="let option of dropdownData[field.field]" [value]="option" style="width: 300px">
<span>{{ option.value }}</span>
<small> | ID: {{option.id}}</small>
</mat-option>
</mat-autocomplete>
Also *.ts has this method:
getDropdownValue(field_name) {
let id = this.model.data[field_name];
for (let i in this.dropdownData[field_name]) {
let option = this.dropdownData[field_name][i];
if (option.id === id) {
console.log("getDropdownValue(): option:", option);
return option;
}
}
console.log("getDropdownValue(): option: null");
return null;
}
Execution log when I change selected items via dropdown menu (without text input):
getDropdownValue()
for input's[value]
gets called multiple times with correct old item (to set composite object as autocomplete's chosen value);getDropdownView()
for mat-autocomplete's[displayWith]
gets called with correct new item (to get shown value from new composite object);onDropdownSelected()
for mat-autocomplete's(optionSelected)
gets called with correct new item (to inform *.ts that option has been chosen);getDropdownValue()
for input's[value]
gets called multiple times again with correct new item.
How can I get right displayWith
instead of [Object Object]
?
getDropdownView
? – Sandeep Kumaroption
on the console? – Sandeep Kumar[Object Object]
only when the value is of object type and not the literal. e.i.{"someKey": "sameValue"}
; hence, what you get on the console will tell you what to return from the function. – Sandeep Kumaroption
is like{"id": 1, "value": "First opt"}
. I want to bind whole object to input but show onlyoption.value
. – Evgeny Nozdrev