Angular - Objects as Select Option Values

本小妞迷上赌 提交于 2021-01-21 12:33:34

问题


I have a form with various select boxes which use objects as the value:

<mat-option [value]="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.

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.

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' }
]

And my .html file:

<mat-select  placeholder="Fruit" [(ngModel)]="item.fruit">
  <mat-option *ngFor="let option of options" [value]="option">{{option.label}}</mat-option>
</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.

I'd like to see something like:

<mat-select          
    placeholder="Fruit" 
    [(ngModel)]="item.fruit" 
    equalityAttr="id"
>

回答1:


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

  public objectComparisonFunction = function( option, value ) : boolean {
    return option.id === value.id;
  }


来源:https://stackoverflow.com/questions/51989366/angular-objects-as-select-option-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!