[英]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.我正在尝试从我的 json 数据动态生成和使用表单控件。 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用于从
demoA
和demoB
获取属性并转换为FomControl
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
的价值是
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?如果我希望结果是
demoC.name
我该怎么做?
Why {{}}
syntax ?为什么是
{{}}
语法? You can bind simply using [(ngModel)]=demoC[demoA]
thi syntax for dynamic property .您可以简单地使用
[(ngModel)]=demoC[demoA]
动态属性的语法进行绑定。 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
.如果您想使用
FormGroup
我认为使用FormControlName
指令而不是ngModel
会更好。 Or if you want to use ngModel
I think you don't need to use FormGroup
with it.或者,如果您想使用
ngModel
我认为您不需要将FormGroup
与它一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.