Angular 8 Select with [(ngModel)] 设置值但文本不显示在选项中
Angular 8 Select with [(ngModel)] sets the value but the text doesn't display in the option
简而言之,我有一个客户端接口:
ClientInterface{
id:number;
displayName: string;
}
然后在一个组件中我有一个客户端数组,以及一个 selected 客户端:
public clients: ClientInterface[];
public selectedClient: ClientInterface = null;
在 ngOnInit 期间,数据从 api 对 PHP 的调用中提取,通过解析器 returns 与接口匹配的 selectedClient 对象,然后将其分配给selectedClient:
ngOnInit() {
// data is taken from the resolver here
// and assigned here
this.selectedClient = <ClientInterface>data.selectedClient;
}
视图有一个下拉菜单:
<select name="client" id="client" class="form-control" [(ngModel)]="selectedClient">
<option *ngFor="let client of clients" [ngValue]="client">{{ client.displayName }}</option>
</select>
好像没有select这个选项??但是,它以另一种方式工作,如果我 select 从下拉列表中选择一个选项, this.selectedClient 在对象中有正确的客户端。
Angular 默认使用对象标识到 select 选项,但在某些情况下,当对象值保持不变但对象标识已更改时,可能会出现差异。为了处理这种情况,angular 提供了 compareWith 输入
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.
试试这个:
component.html
<select [compareWith]="compareFn" name="client" id="client" class="form-control" [(ngModel)]="selectedClient">
<option *ngFor="let client of clients" [ngValue]="client">{{ client.displayName }}</option>
</select>
component.ts
compareFn(c1: any, c2: any): boolean {
return c1 && c2 ? c1.selectedClient === c2.selectedClient : c1 === c2;
}
简而言之,我有一个客户端接口:
ClientInterface{
id:number;
displayName: string;
}
然后在一个组件中我有一个客户端数组,以及一个 selected 客户端:
public clients: ClientInterface[];
public selectedClient: ClientInterface = null;
在 ngOnInit 期间,数据从 api 对 PHP 的调用中提取,通过解析器 returns 与接口匹配的 selectedClient 对象,然后将其分配给selectedClient:
ngOnInit() {
// data is taken from the resolver here
// and assigned here
this.selectedClient = <ClientInterface>data.selectedClient;
}
视图有一个下拉菜单:
<select name="client" id="client" class="form-control" [(ngModel)]="selectedClient">
<option *ngFor="let client of clients" [ngValue]="client">{{ client.displayName }}</option>
</select>
好像没有select这个选项??但是,它以另一种方式工作,如果我 select 从下拉列表中选择一个选项, this.selectedClient 在对象中有正确的客户端。
Angular 默认使用对象标识到 select 选项,但在某些情况下,当对象值保持不变但对象标识已更改时,可能会出现差异。为了处理这种情况,angular 提供了 compareWith 输入
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.
试试这个:
component.html
<select [compareWith]="compareFn" name="client" id="client" class="form-control" [(ngModel)]="selectedClient">
<option *ngFor="let client of clients" [ngValue]="client">{{ client.displayName }}</option>
</select>
component.ts
compareFn(c1: any, c2: any): boolean {
return c1 && c2 ? c1.selectedClient === c2.selectedClient : c1 === c2;
}