问题描述
我有一个带有各种选择框的表单,这些选择框使用对象作为值:
I have a form with various select boxes which use objects as the value:
当我通过表单创建新记录时,这非常有用.现在,当我编辑记录时,我遇到了 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
中的 'pineapple' 和 options
数组没有指向同一个 'pineapple' 对象 - 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>
打字稿
public objectComparisonFunction = function( option, value ) : boolean {
return option.id === value.id;
}
这篇关于Angular - 对象作为选择选项值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!