【问题标题】:ngModel doesn't display the value of an object in mat-selectngModel 不显示 mat-select 中对象的值
【发布时间】:2018-09-04 08:38:46
【问题描述】:

我有一个公司类,它有一个总部地址字段。地址是一个接口,它有另一个对象,country,它是另一个接口。 在我的数据库中,我存储了所有国家/地区。我有一个编辑选定公司的视图,在那里我可以设置或更改总部地址,并为国家/地区创建了一个 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,那么它可以正常工作,但是要存储国家/地区的代码或名称,我必须编写一个方法,它会找到country 通过 companyService.countries 数组中的 id 并将这个国家设置为 company.headquarter.country 的字段。所以这不是一个好的解决方案。

【问题讨论】:

标签: angular angular5 angular2-forms angular4-forms


【解决方案1】:

[(ngModel)] 更改为[(value)]

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

【讨论】:

  • 同样的问题。使用此解决方案将国家/地区保存到 company.headquarter.country 正在工作,但是当我想编辑时,mat-select 不显示当前值。
  • 你的 mat-select 在 mat-form-field 内吗?
  • 是的,它在 mat-form-field 内。链接失效了!
  • 也可能是对象身份问题。请记住,在 js { hello: 'world' } !== { hello: 'world } 中,我建议将 select 绑定到标量值。
【解决方案2】:

此代码将所选国家/地区保存到总部所在国家/地区 字段,但如果我想编辑同一家公司,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>

代码:

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

Official Doc

【讨论】:

  • 酷!乐于助人?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
  • 2019-11-29
  • 2019-07-03
  • 2021-12-24
  • 2018-03-21
  • 2021-07-29
相关资源
最近更新 更多