Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a dynamic property in ngModel inside ngFor, with Angular 2

Tags:

angular

I have a component with :

  • "selectedData" : any
  • "fields" : An array of fields. A field is an object with these properties : label and type. These fields describe the object "selectedData"

Example :

selectedData = { Label:"test", IsUsed:false}

fields = [{name:'label', type:'string'},{name:'IsUsed, type:'boolean'}

I am trying to generate a form for editing the data inside 'selectedData'

Here is the part of my view :

 <div class="ui-grid-row" *ngFor="let myField of fields" >
            <div class="ui-grid-col-4"><label for="{{myField.name}}">{{myField.name}}</label></div>
            <div class="ui-grid-col-8"><input pInputText id="{{myField.name}}" [(ngModel)]="this['selectedData.' + myField.name]" /></div>
        </div>

The problem is with this line

[(ngModel)]="this['selectedData.' + myField.name]"

It does not work as I wanted. Here is the Google Chrome watch of my component when i edit : screen capture of my problem

As you can see, Angular2 creates an object with name "selectedData.Label" instead of using the selectedData existing object.

Is there a solution? Or should I do it differently?

Thx

like image 534
Sylvain Reverdy Avatar asked Dec 23 '16 21:12

Sylvain Reverdy


1 Answers

The answer was easy :

[(ngModel)]="selectedData[myField.name]"

If field.Name has a value of 'label', the previous code is equivalent as :

[(ngModel)]="selectedData.label"

I did not know that the '[ ]' could be used this way.

like image 116
Sylvain Reverdy Avatar answered Oct 18 '22 17:10

Sylvain Reverdy