[英]Set key and value in angular form
最初,我有一個像這樣的簡單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,我需要創建在結果數組中給出鍵和值的輸入框。
使用上面的我需要設置輸入框的鍵和值,
所以它會喜歡,
關鍵dataOneValue => value 12cm
關鍵數據TwoValue => value 10cm
在這里,我僅給出2個只是為了理解,但它不是靜態的。.,它可能會根據結果數組具有的對象數而變化。
那么如何從json的result
數組中將鍵和值設置為輸入框呢?
Stackblitz https://stackblitz.com/edit/angular-x7mda4
也許這會有所幫助:
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);
}
這應該通過動態構建表單來與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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.