Reputation: 818
I got a select were options is fetched from BE, once fetched I populate the options. The ngModule was set in another step and is equal to one of the options. This result im looking for is that that option that is the same as my modle is shown.
<select class="form-control" id="accident-" [(ngModel)]="accident" required>
<option *ngFor="let a of accidents" [ngValue]="a">{{a.text | titlecase}}</option>
</select>
Br
Upvotes: 0
Views: 60
Reputation: 3021
Angular uses object identity to select option.
To customize the default option comparison algorithm, <select>
supports compareWith
input.
HTML file:
<select class="form-control" id="accident-" [(ngModel)]="accident" required [compareWith]="byAccident">
<option *ngFor="let a of accidents" [ngValue]="a">{{a.text | titlecase}}</option>
</select>
TS file:
byAccident(item1, item2) {
return item1 && item2 ? item1.text === item2.text : item1 === item2;
}
Reference: https://angular.io/api/forms/SelectControlValueAccessor#caveat-option-selection
Upvotes: 2
Reputation: 1517
Please add an id
property to accident objects and then,
<select class="form-control" id="accident-" [(ngModel)]="selectedAccident.id" required>
<option *ngFor="let a of accidents" [ngValue]="a.id">{{a.text | titlecase}}
</option>
</select>
Here you have to set the selectedAccident
according to your business requiremet in TS file
Upvotes: 2