我知道像这样的问题已经问过了,但对我来说没有结果。实际上,我有很大的嵌套json值,如下所示:
"Q-1": {
"question": {
"text": "What are your hopes and goals for this year? (This could be about family, friends, community, faith, work, education, health, or more.)",
"bounding-box": []
},
"answer": {
"original": {
"handwritten-text": {
"value": "",
"bounding-box": []
}
}
},
"page": {
"page_no": "",
"page_dim": [],
"accuracy_score": ""
}
},
"Q-2": {
"question": {
"text": "What things in your life bring you the most happiness?",
"bounding-box": []
},
"answer": {
"original": {
"handwritten-text": {
"value": "",
"bounding-box": []
}
}
},
"page": {
"page_no": "",
"page_dim": [],
"accuracy_score": ""
}
},
..................现在,我想根据这个JSON值创建一个反应性,如下所示:
this.userForm= this.fb.group({
Q1: new FormGroup({
answer: new FormGroup({
original: new FormGroup({
"handwritten-text": new FormGroup({
value: new FormControl(''),
"bounding-box": new FormControl('')
})
})
})
}),
Q2: new FormGroup({
answer: new FormGroup({
original: new FormGroup({
"handwritten-text": new FormGroup({
value: new FormControl(''),
"bounding-box": new FormControl('')
})
})
})
}),
})
})因此,我认为我必须首先遍历大型嵌套的json值,然后创建不同的方法,使用适当的键和值创建FormGroup,然后将formGroup推到原始的formArray,但是在实现它时我遇到了问题。
还有其他简单的方法吗。
发布于 2022-01-24 14:47:22
是的,您的解决方案看起来很复杂,我最近做了一些类似的事情,我用接口解决了问题,例如:
"question": {
"text": "What are your hopes and goals for this year? (This could be about family, friends, community, faith, work, education, health, or more.)",
"bounding-box": []
},
"answer": {
"original": {
"handwritten-text": {
"value": "",
"bounding-box": []
}
}
}用户只需键入“边界框”、“值”和“文本”.您可以使用一个简单的表单(不嵌套)获取数据,并在component.ts中按照接口的要求重新组织所有数据.
下面是我解决的一个例子:
接口
export interface PieInterface{
dataSet:PieDataSet,
labels: string[],
title: string
}
export interface PieDataSet{
backgroundColor: string[],
data: number[]
}组件
myForm: FormGroup = this.fb.group({
//single values
title: [],
pointsQuantity: [, [Validators.required, Validators.min(1)]],
//arrays
labels: this.fb.array([["", Validators.required],], Validators.required),
data: this.fb.array([["", Validators.required],], [Validators.required, Validators.min(0)]),
backgroundColor: this.fb.array([["#24C5E0", Validators.required],], Validators.required),
})
setValues(){
if(this.myForm.valid){
const dataSet: PieDataSet = {
backgroundColor: this.myForm.controls.backgroundColor.value,
data: this.myForm.controls.data.value
}
const myChart: PieInterface =
{
title: this.myForm.controls.title.value,
labels: this.myForm.controls.labels.value,
dataSet: dataSet
}
this.pieService.data$.emit(myChart)
}}https://stackoverflow.com/questions/70833400
复制相似问题