Set dynamic property to ngModel inside ngFor, with Angular 2

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 "selectedData" object.

An example :

selectedData = { Label:"test", IsUsed:false} fields = [{name:'label', type:'string'},{name:'IsUsed, type:'boolean'} 

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

Here is 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> 

Problem with this line

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

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

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

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

thanks

+5
source share
1 answer

The answer is simple:

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

If field.Name is "label", the previous code is equivalent to:

 [(ngModel)]="selectedData.label" 

I did not know that "[]" could be used in this way.

+6
source

Source: https://habr.com/ru/post/1261798/


All Articles