我有一个像这样的Json数据:
assets/details.json
{
"name" : "john",
"age" : 20,
"address" : [{
"main": "address1",
"sub": "address2"
},
{
"main": "add1",
"sub" : "add2"
}]
}
我想用patchValue以角度形式显示所有json数据。
我已经尝试过了。
app.component.ts
export class AppComponent {
data: FormGroup
constructor(private FB: FormBuilder, private service: DataService) {}
ngOnInit() {
this.data = this.FB.group({
name: [''],
age: [''],
address: this.FB.array([
this.addAddress()
])
})
this.getData()
}
addAddress(): FormGroup {
return this.FB.group({
main: [''],
sub: [''],
})
}
}
getData(){
this.service.getData('../assets/details.json').subscribe( (data) => {
this.data.patchValue({data})
}
}
我已经这样设计HTML页面:
app.component.html
<form [formGroup]="data" (ngSubmit)="onSubmit()">
<input formControlName="name" type="text" class="form-control col-sm-8">
<input formControlName="age" type="number" class="form-control col-sm-8">
<div formArrayName="address" *ngFor="let d of data.get('address').controls; let i = index;">
<div [formGroupName]="i">
<input formControlName="main" type="text" class="form-control">
<input formControlName="sub" type="text" class="form-control" />
</div>
</div>
</form>
但是没有任何效果如我所料。没有什么可以填写表格。我不知道该怎么做。
如何在表单字段中获取所有这些json数据?
感谢您的帮助。
答案 0 :(得分:0)
如果您的表单中没有FormArray
,则可以只使用this.data.patchValue(data)
(如果所有属性都匹配,则可以使用setValue
),但是由于您有一个formarray,因此需要遍历对象中的address
数组并将表单组推入表单数组。另外,我认为在构建表单时不需要最初创建一个空的表单组,因此我将其省略了:
ngOnInit() {
this.data = this.FB.group({
name: [''],
age: [''],
address: this.FB.array([])
})
}
get formArr() {
return this.data.get('address') as FormArray;
}
// ....
this.data.patchValue({name: data.name, age: data.age});
data.address.forEach((x) => {
this.formArr.push(this.FB.group(x))
});
答案 1 :(得分:0)
patchValue
仅更新现有的FormArray
,而不会修改您的FormArray
的结构。修补之前,必须确保FormArray
的大小正确,也可以完全重新创建它,如下所示:
this.data.patchValue({ name: data.name, age: data.age });
this.data.controls['address'] = this.FB.array(data.map(address => {
const group = this.addAddress();
group.patchValue(address);
return group ;
}));
答案 2 :(得分:0)
this.formCustomer.patchValue({ ...response.data })
response.data.contactos.forEach(c => {
this.contactos.push(this.Contact(c))
});
get contactos(): FormArray {
return <FormArray>this.formCustomer.get("contactos")
}
Contact(item?:any): FormGroup {
return this.fb.group({
tipo: [item?item.tipo:'', [Validators.required]],
nombre: [item?item.nombre:'', [Validators.required]],
tel: [item?item.tel:'', [Validators.required]],
tel_2: [item?item.tel_2:''],
})
}
this.formCustomer = this.fb.group({
contactos: this.fb.array([this.Contact()]),
})
答案 3 :(得分:-1)
getData()
方法的工作方式如下:
getData() {
this.service.getData('../assets/details.json').subscribe((_data) => {
this.data.patchValue(data)
(this.data as FormGroup).setControl('address', this.fb.array(this.data.address || []);
}
}