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?
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 withFormGroupI think it will be better to useFormControlNamedirectives instead of thengModel. Or if you want to usengModelI think you don't need to useFormGroupwith it.