简体   繁体   中英

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

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 FomControl s

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.name How do I go about doing this?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM