Reputation: 917
in short, i have an interface for a client:
ClientInterface{
id:number;
displayName: string;
}
Then in a component i have an array of clients, and a single selected client:
public clients: ClientInterface[];
public selectedClient: ClientInterface = null;
During ngOnInit data is pulled from an api call to PHP via a resolver which returns the selectedClient object that matches the interface, then assigns it to the selectedClient:
ngOnInit() {
// data is taken from the resolver here
// and assigned here
this.selectedClient = <ClientInterface>data.selectedClient;
}
The view has a dropdown:
<select name="client" id="client" class="form-control" [(ngModel)]="selectedClient">
<option *ngFor="let client of clients" [ngValue]="client">{{ client.displayName }}</option>
</select>
It doesn't seem to be selecting the option?? It works the other way though, if i select an option from the drop down, this.selectedClient has the correct client in the object.
Upvotes: 1
Views: 1878
Reputation: 27471
Angular uses object identity by default to select options but in some scenarios there can be discrepancies when object values remains same but object identity is changed. To handle such scenarios, angular provides 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.
Try this:
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;
}
Upvotes: 1