Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

javascript - 如何显示名称,但从mat-autocomplete select对象的对象中获取其他属性的值? 角-角材料(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))   ask by AleksandarMihailovic translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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示例,以使其更加简化。) Example() 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选项中,并将整个对象作为值提供) <mat-option *ngFor="let option of options" [value]="option" > {{option.name}} </mat-option> Please check the stackblitz example for more details(请检查stackblitz示例以获取更多详细信息)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...