[英]How to display a name but take the values of some other property from the object from mat-autocomplete select? Angular- Angular Material
I spent a lot of time solving this problem and failed.我花了很多时间解决这个问题,但失败了。 I want to select to display the name and get the id.
我想选择显示名称并获取ID。 The problem is, as soon as a value is selected, the number (id) of that value is displayed.
问题是,只要选择了一个值,就会显示该值的编号 (id)。 My code:
我的代码:
<mat-form-field class="example-full-width">
<input
matInput
placeholder="Search your product"
formControlName="id"
[matAutocomplete] = "auto">
<mat-autocomplete #auto="matAutocomplete" >
<mat-option *ngFor="let option of allProducts; let i = index" [value]="option.id" >
{{ option.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
I tried to create a function (onSelectionChange) but could not display the name and take the value as (id)我试图创建一个函数 (onSelectionChange) 但无法显示名称并将值作为 (id)
Well, you have to use the input function of auto-complete called displayWith
.好吧,您必须使用名为
displayWith
的自动完成输入功能。
you can find the solution to your problem in this link here 您可以在此链接中找到问题的解决方案
plus I 've made a stackblitz example for you to simplify it more.另外,我为您制作了一个 stackblitz 示例,以进一步简化它。
to describe the solution:描述解决方案:
you have to add to your autocomplete component an input called displayWith您必须向自动完成组件添加一个名为 displayWith 的输入
<mat-autocomplete #auto="matAutocomplete" [displayWith]="checkValue">
and then in your component you have to create the function checkValue然后在您的组件中,您必须创建函数 checkValue
checkValue(value: any) {
// here you can get your id or whatever you want
console.log(value)
}
then you have to add to your mat option the value and give it your whole object as value然后您必须将值添加到您的垫子选项中,并将您的整个对象作为值
<mat-option *ngFor="let option of options" [value]="option" >
{{option.name}}
</mat-option>
Please check the stackblitz example for more details 请查看 stackblitz 示例以获取更多详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.