角度-对象作为选择选项值 [英] Angular - Objects as Select Option Values
问题描述
我有一个带有各种选择框的表单,这些选择框使用对象作为值:
I have a form with various select boxes which use objects as the value:
< mat-option [value] ="object">
当我通过表单创建新记录时,哪一个工作得很好?现在,当我编辑记录时,遇到了一个问题,即 mat-select-option
中的 object
不是我从休息服务中获得的相同"对象,因此在编辑记录时我的选择框没有选择任何选项.
Which works great when I am creating new records via the form. Now when I am editing records, I run into the problem that the object
in the mat-select-option
is not the "same" object that I get from my rest service, so my select boxes have no option selected when editing the record.
在决定选择哪个选项时,是否可以告诉选择框窗口小部件在 object.id
上匹配?我想我可能需要编写一条指令来处理此问题,但是对于Angular或Angular Material库或其他现有解决方案,这可能已经成为可能.
Is it possible to tell the select-box widget to match on object.id
when deciding what option is selected? I think I may need to write a directive to handle this, but maybe this is already possible with Angular or Angular Material libraries, or another existing solution.
为了详细说明,我有我的 foo.component.ts
文件:
To elaborate I have my foo.component.ts
file:
let item = {
'fruit': { id: 1, 'label': 'Pineapple' },
}
let options = [
{ 'id':1, 'label': 'Pineapple' },
{ 'id':2, 'label': 'Banana' },
{ 'id':3, 'label': 'Papaya' }
]
和我的 .html
文件:
<mat-select placeholder="Fruit" [(ngModel)]="item.fruit">
<mat-option *ngFor="let option of options" [value]="option">{{option.label}}</mat-option>
</mat-select>
当用户访问页面时,他们应该看到在 mat-select
中选择的菠萝".因为 item.fruit
中的菠萝"和 options
数组未指向相同的菠萝"对象- mat-select
是空的.
When the user visits the page, they should see "Pineapple" selected in the mat-select
. Because the 'pineapple' in the item.fruit
and the options
array are not pointing to the same 'pineapple' object - the mat-select
is empty.
我想看到类似的东西:
<mat-select
placeholder="Fruit"
[(ngModel)]="item.fruit"
equalityAttr="id"
>
推荐答案
它是 [compareWith]
指令.Angular.io目前处于关闭状态,因此我将使用此中篇供参考.
It is the [compareWith]
directive. Angular.io is down at the moment, so I will ink to this medium article for reference.
HTML
<mat-select
placeholder="Fruit"
[(ngModel)]="item.fruit"
[compareWith]="objectComparisonFunction">
<mat-option *ngFor="let option of options" [value]="option">{{option.label}}</mat-option>
</mat-select>
TypeScript
TypeScript
public objectComparisonFunction = function( option, value ) : boolean {
return option.id === value.id;
}
这篇关于角度-对象作为选择选项值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!