How can I bind 2 variables inside 1 property binding in angular 2?

1.6k views Asked by At

I'm trying to dynamically generate and use form controls from my json data. A simple experiment I came up with to figure out the mechanics I need to apply goes as follows.

variables defined in class

demoA: string         = 'name';
demoB: Array<string>  = ['city', 'state'];
demoC: FormGroup      = new FormGroup({});

function for grabbing properties from demoA and demoB and converting into FomControls

loadStuff(){
    let a = this.demoA;
    let b = this.demoB;
    let ab: Array<string> = [];

    ab.push(a);
    b.forEach( bb => {ab.push(bb)} );
    console.log(ab);

    ab.forEach( ctrl => this.demoC.addControl(ctrl, new FormControl('')) );

    console.log( this.demoC.value );
}

Now the value of demoC is

demoC: {name:'', city:'', state:''}

Due to the fact that I'm creating this on the fly when my component loads, there's no predefined way for me to bind to it, which led me to wonder if I can bind to it inside the binding on the input something like this

<input type="text" [(ngModel)]="demoC.{{demoA}}" />

of course that didn't work, neither did

<input type="text" [(ngModel)]="demoC.[demoA]" />

<input type="text" [(ngModel)]="demoC.[(demoA)]" />

<input type="text" [(ngModel)]="demoC.(demoA)" />

<input type="text" [(ngModel)]="(demoC)+'.'+(demoA)" />

<input type="text" [(ngModel)]="[(demoC)+'.'+{{demoA}}]" />

<input type="text" [(ngModel)]="('demoC.'+{{demoA}})" />

<input type="text" [(ngModel)]="['demoC.'+{{demoA}}]" />

<input type="text" [(ngModel)]="['demoC.'+[demoA]]" />

<input type="text" [(ngModel)]="[('demoC.')+[demoA]]">

If I want the result to be demoC.nameHow do I go about doing this?

1

There are 1 answers

2
Suren Srapyan On

Why {{}} syntax ? You can bind simply using [(ngModel)]=demoC[demoA] thi syntax for dynamic property. But you have mixed two approaches here Simple Form approach vs Reactive Form approach. If you want to work with FormGroup I think it will be better to use FormControlName directives instead of the ngModel. Or if you want to use ngModel I think you don't need to use FormGroup with it.