Angular2/4 mat-select多个ngModel

Mai*_*das 6 angular-material angular2-forms angular2-ngmodel angular

我有一个mat-select下拉列表,启用了多个,我使用NgModel来存储用户选择的值.

问题是,当我导航到另一个页面并返回时,用户选择的值不在mat-select中..我知道ngModel有这些值...我遗漏了一些东西......

HTML

<mat-form-field>
 <mat-select placeholder="Customers" name="customerDetails" ngDefaultControl       
 formControlName="customerDetails" [(ngModel)]="custonerDetails" 
 [formControl]="customerDetailsCtrl" multiple   
 (ngModelChange)="onCustomerValueChanges(customer)" >

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

有任何想法吗?

Red*_*ree 9

根据用例初始化,选择的某些默认选项可能无法通过简单地绑定到ngModel,因为选项中的对象和前一状态的选定子集中的对象具有不同的标识.由于支持compareWith它可以将它们设置为选中.

这里看一下官方的Angular文档.

在Material2演示应用程序中,他们有一个具有两个实现的函数示​​例.就在这里.

在我的组件中,我有一组用户对象[people]用于mat select的选项.组件从先前状态接收所选用户对象[用户]的集合作为输入.足够公平,[人]中的对象和[用户]中的对象具有不同的身份,并且默认情况下,多选中的子集不会使用所选复选框进行初始化.

因此,魔法compareWith只是通过某些给定值比较对象并返回true或false,并且[people]子集上的复选框获得所选状态.在我的代码中,我决定使用[(ngModel))绑定:

<mat-form-field>
    <mat-select [compareWith]="compareFn" name="users" [(ngModel)]="users" multiple>
        <mat-option *ngFor="let person of people" [value]="person">
           {{ person.username }}
        </mat-option>
   </mat-select>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

在.ts文件中,我利用Angular doc中的函数返回true,如果两个User对象具有相同的id:

compareFn(user1: User, user2: User) {
    return user1 && user2 ? user1.id === user2.id : user1 === user2;
}
Run Code Online (Sandbox Code Playgroud)

如果你有一个类似的用例,它可能是开箱即用的.

关于引擎盖下的注意事项,compareWith让我很好奇.我发现它基于Angular2中一个名为looseIdentical的函数(看看这里),而这个函数又来自谷歌在Dart.js库中的相同内容.它可以在这里找到.


小智 -2

如果您确定 ngModel 具有其中的值。问题可能是 mat-option 的 [value] 属性丢失了此选择。

尝试这个:

[ngValue]="customer" instead of [value]= "customer"
Run Code Online (Sandbox Code Playgroud)