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


i converting angular 1.6 code angular 4 , have issue list of elements. code in angular 1.6 is:

<select ng-model="$ctrl.level" ng-options="item item.label item in $ctrl.referentiel.levels | orderby : 'index' track item.id"                                   id="childlevel" name="childlevel" class="size-xl"                               > <option value="">select</option> </select> 

the object level not referenced in list because list loaded using object referentiel.levels. matching between elements of list , object level done trackby. when object level loaded, element selected in list.

now, try convert code using reactive forms. in html code, have:

<select formcontrolname="levelcontrol" id="levelselect" name="levelselect" class="size-xl"> <option [ngvalue]="null">select</option> <option *ngfor="let level of referentiel.levels;trackby:identify" [ngvalue]="level">{{level.label }}</option> </select> 

and in component, have in oninit method:

(<formcontrol>this.myform.controls.levelcontrol).setvalue(this.level); 

and method identify simple:

identify(index,item){    return item.id; } 

but comportment different. when set value of control using object level, item same id in list not selected.

i found solution don't understand why not working. workaround write code in html:

<option *ngfor="let level of referentiel.levels;trackby:identify" [ngvalue]="level.id">{{level.label }}</option> 

and in typescript file:

(<formcontrol>this.myform.controls.levelcontrol).setvalue(this.level.id); 

so, working: item selected in list.

i don't understand difference between 2 versions of angular in case. maybe missed something...

thanks help.

i don't see need trackby here, unless want use it. has nothing why default option not working.

why works level.id because string (number ?) whereas level object has no reference array, therefore cannot recognized list.

since using angular 4, have new directive [comparewith] can compare property level, example id. compare array , find match. can 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 changed

<option [ngvalue]="null">select</option> 

to

<option value="">select</option> 

so angular not trying compare null value. throw error.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -