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

标签 angular angular5 angular2-forms angular4-forms

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

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

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

已编辑:

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

最佳答案

This code save the selected country to the headquarter's country field, but if I want to edit the same company the mat-select doesn't display the actual value. how can I solve this problem?



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

To customize the default option comparison algorithm, supports compareWith input. compareWith takes a function which has two arguments: option1 and option2. If compareWith is given, Angular selects option by the return value of the function.



模板:
 <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>

代码:
 compareById(f1: Common.Item, f2: Common.Item): boolean {
     return f1 && f2 && f1.id === f2.id;
 }

Official Doc

关于angular - ngModel 不显示 mat-select 中对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49487435/

相关文章:

angular - 转换不适用于 angular5 动画

angular - 在子组件中更新值,在父组件中更改值时

forms - Angular 2 : add and submit a new formGroup name and values with model driven form

angular - Angular 2 中的表单控件

Angular 2 表单验证 : fields inside components

angular - Angular 的组件名称相同

angular - Tslint - 类型简单推断 - 为什么在此处包含类型是不好的做法?

html - 在单个页面中处理多个 NgbPagination

node.js - Electron --serve在缺少package.json时失败

firebase - 错误 TS2339 : Property 'firebaseConfig' does not exist on type '{ production: boolean; }'