最初,我有一个简单的 JSON ,
jsonData = {
status : "true",
message: "Dynamic creation of input boxes and patch its value",
result: [
{
"dataOneValue": "12cm"
},
{
"dataTwoValue": "10cm"
}
]
}
还有ngOnInit
,
ngOnInit() {
this.jsonData.result.forEach(element => {
console.log(element);
});
使用此JSON,我需要创建在 result 数组中给出键和值的输入框。
使用上述代码,我需要为输入框设置键和值,
它会喜欢的,
键 dataOneValue =>值 12厘米
键 dataTwoValue =>值 10cm
这里我仅给出2个用于理解,但它不是静态的..,它可能会根据结果数组具有的对象数而有所不同。
那么如何从result
数组的json设置键和值到输入框?
答案 0 :(得分:1)
也许这会有所帮助:
https://stackblitz.com/edit/angular-z6fuog
<form [formGroup]="form">
<span *ngFor="let control of controls">
<input type="text" [formControlName]="control" placeholder="dataOneValue">
<br><br>
</span>
</form>
ngOnInit() {
// firstName: ['', Validators.required],
let _controls = {};
this.jsonData.result.forEach(element => {
let key = Object.keys(element)[0];
let control = [element[key], Validators.required];
_controls[key] = control;
this.controls.push(key);
//console.log(_controls);
});
this.form = this.formBuilder.group(_controls);
}
答案 1 :(得分:0)
这应该通过动态构建表单来与Reactive表单一起使用:
https://stackblitz.com/edit/angular-x7mda4
在app.component.ts
中get resultForms() {
return this.resultForm.get('results') as FormArray
}
ngOnInit() {
this.resultForm = this.fb.group({
results: this.fb.array([ ]),
});
this.jsonData.result.forEach(element => {
const resultGroup = this.fb.group({
value: element[Object.keys(element)[0]]
})
this.resultForms.push(resultGroup);
});
}
在app.component.html
中<form [formGroup]="resultForm">
<div formArrayName="results">
<div *ngFor="let result of resultForms.controls; let i=index" [formGroupName]="i">
<input formControlName="value">
</div>
</div>
</form>