简体   繁体   English

Angular 6+ 材料框架选择提供的值

[英]Angular 6+ material framework select with provided value

I'm trying to use mat-select with backend based search, but there is a problem when reloading data.我正在尝试将 mat-select 与基于后端的搜索一起使用,但是在重新加载数据时出现问题。 I'm using object like {value: 1, name: 'aloha'} to store and display value.我正在使用像 {value: 1, name: 'aloha'} 这样的对象来存储和显示值。 And I want to pass .value as an value in option.我想将 .value 作为选项中的值传递。 Currently I'm stuck at passing whole value and using it to create option with this data to have display value in select.目前我坚持传递整个值并使用它来创建带有此数据的选项以在选择中显示值。 Is there a better way to do this?有一个更好的方法吗? And second question, I'm using this select in formcontrol.第二个问题,我在formcontrol中使用这个选择。 How do I set initial value when there are no options in select but I need to have initial provided selected option. How do I set initial value when there are no options in select but I need to have initial provided selected option. Like I have on backend [cat, dog, elephant] and milion other values but I need to preselect cat for instance.就像我在后端 [猫、狗、大象] 和 milion 其他值一样,但我需要例如预选 cat。 Like new FormControl(cat).像新的 FormControl(cat)。 I could live with passing FormControl({value: 5, display: cat}) but is there a way to get control.value of only value from this object?我可以忍受传递 FormControl({value: 5, display: cat}) 但是有没有办法从这个对象中获取只有值的 control.value ? I dont want it to return whole object ({name, value})我不希望它返回整个对象 ({name, value})

First question.第一个问题。

<mat-select placeholder="Placeholder" formControlName="yourForm">
    <mat-option *ngFor="let x of yourArray" [value]="x.value">
        {{ x.name }}
    </mat-option>
</mat-select>

You can use [value] to save its value and use interpolation to display desired value (ie {{x.name}} ).您可以使用[value]来保存它的值并使用插值来显示所需的值(即{{x.name}} )。

Second question.第二个问题。

Above set-up takes care of #2.以上设置负责#2。 You can now use FormControl({value: 5, display: cat})您现在可以使用FormControl({value: 5, display: cat})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM