gpt4 book ai didi

Angular AutoComplete 将返回值作为 [Object Object]

转载 作者:行者123 更新时间:2023-12-03 14:34:52 24 4
gpt4 key购买 nike

我的要求是在输入框中显示选定的值并将选定的 Id 和值获取到 .ts 文件。由于我需要 Id 和 Value,我将选项值直接绑定(bind)到 [value]。但如果我这样做,它会被打印为 [Object Object]。

<mat-form-field appearance="outline" class="w-100">
<mat-label>Enter Hotel Name</mat-label>
<input type="text" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selectedclient($event)">
<mat-option *ngFor="let option of clients; let i = index" [value]="option">
{{ option.name }}
</mat-option>
</mat-autocomplete>
<mat-icon matSuffix>location_on</mat-icon>
</mat-form-field>

TS文件
    options = [
{ id: 1, name: 'One'},
{ id: 2, name: 'Two'},
{ id: 3, name: 'Three'}
];

selectedclient(event) {
console.log(event.option.value);
}

Stackblitz 编辑器网址:
https://stackblitz.com/edit/angular-mat-select-data-n4tvmj

最佳答案

您想使用 displayWith 属性。根据手册:

If you want the option's control value (what is saved in the form) to be different than the option's display value (what is displayed in the text field), you'll need to set the displayWith property on your autocomplete element. A common use case for this might be if you want to save your data as an object, but display just one of the option's string properties.

To make this work, create a function on your component class that maps the control value to the desired display value. Then bind it to the autocomplete's displayWith property.



模板面
<mat-autocomplete ... [displayWith]="getOptionText">

脚本端
getOptionText(option) {
return option.name;
}

演示:https://stackblitz.com/edit/angular-mat-select-data-cddqia

关于Angular AutoComplete 将返回值作为 [Object Object],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55099125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com