Issue
I have a select inside a custom component that loads a lot of options from database and I bind options like this:
<select [id]="id" class="form-control" [formControlName]="id">
<option *ngFor="let p of items | async" [value]="codeKey">
{{ p[labelField] }}
</option>
</select>
In parent component ngOnInit
I’m loading the entity from database and I need to bind the id with an option inside the select. The binding fails if the select inside (child) custom component takes too much time to load his options.
Is there a method to bind the id only when the custom component has loaded his data?
Solution
You could use compareWith input on select element. If we give compareWith function to select element then Angular selects option by the return value of the function.
component.html
<select [compareWith]="compareFn" [id]="id" class="form-control" [formControlName]="id">
<option *ngFor="let p of items | async" [value]="codeKey">
{{ p[labelField] }}
</option>
</select>
component.ts
compareFn(c1, c2): boolean {
return c1 && c2 ? c1.id === c2.id : c1 === c2;
}