Angular 4 - Reactive Forms - select item in a list from object not referenced in this list - trackby issue? Angular 4 - Reactive Forms - select item in a list from object not referenced in this list - trackby issue? angular angular

Angular 4 - Reactive Forms - select item in a list from object not referenced in this list - trackby issue?


I don't see that you would need the trackBy here, unless you want to use it. But it has nothing to do with why your default option is not working.

Why it works with level.id is because this is a string (number ?) whereas level is an object that has no reference to your array, therefore it cannot be recognized from the list.

Since you are using Angular 4, we now have a new directive [compareWith] where we can compare some property from your level, for example the id. Compare it with the array and find a match. So what you can do is the following:

<select formControlName="levelControl" [compareWith]="compare"   id="levelSelect" name="levelSelect" class="size-xl">    <option value="">Select</option>    <option *ngFor="let level of referentiel.levels" [ngValue]="level">      {{level.label }}    </option></select>

component:

compare(val1, val2) {  return val1.id === val2.id;}

Also notice that I changed

<option [ngValue]="null">Select</option>

to

<option value="">Select</option>

so that Angular is not trying to compare to a null value. That would throw an error.