ngModel 不会在 mat-select 中显示对象的值

Ano*_*oat 3 angular2-forms angular angular4-forms angular5

我有一个公司类,它有一个总部的地址字段。地址是一个接口,它有另一个对象,国家,这是另一个接口。在我的数据库中,我存储了所有国家。我有一个编辑选定公司的视图,在那里我可以设置或更改总部的地址,并为国家/地区创建了一个 mat-select:

<mat-select [(ngModel)]="company.headquarter.country">
    <mat-option *ngFor="let country of companyService.countries" [value]="country">
        {{country.name}}
    </mat-option>
</mat-select>
Run Code Online (Sandbox Code Playgroud)

此代码将所选国家/地区保存到总部的国家/地区字段,但如果我想编辑同一家公司,则 mat-select 不会显示实际值。我怎么解决这个问题?

编辑:

如果我将 ngModel 更改为 company.headquarter.country.id 并将 [value] 更改为 country.id,那么它可以正常工作,但是要存储国家/地区的代码或名称,我必须编写一个方法,该方法将通过在 companyService.countries 数组中输入 id 并将这个国家设置为 company.headquarter.country 的字段。所以这不是一个好的解决方案。

Yer*_*kon 8

此代码将所选国家/地区保存到总部的国家/地区字段,但如果我想编辑同一家公司,则 mat-select 不会显示实际值。我怎么解决这个问题?

问题是当您 mat-select 比较两个对象时,它们的引用可能不同。用于compare function通过一些标记来比较您的对象,例如id

自定义默认选项比较算法,支持compareWith输入。compareWith接受一个有两个参数的函数:option1 和 option2。如果compareWith给定,Angular 根据函数的返回值选择选项。

模板:

 <mat-form-field>
              <mat-select [(value)]="contract.company"
                          panelClass="example-panel-dark-blue"
                          [compareWith]="helper.compareById">

                <mat-option *ngFor="let cust of customers"
                            [value]="cust"> {{cust.title}}
                </mat-option>
              </mat-select>
  </mat-form-field>
Run Code Online (Sandbox Code Playgroud)

代码:

 compareById(f1: Common.Item, f2: Common.Item): boolean {
     return f1 && f2 && f1.id === f2.id;
 }
Run Code Online (Sandbox Code Playgroud)

官方文件