在ngx formly的帮助下,数组Angular 9中的动态形式
尝试实现:使用ngx formly/material根据用户选择的区域设置JSON实现动态表单。如何用我的对象数组“this.fields2”映射字段 在my component.ts中,我有:在ngx formly的帮助下,数组Angular 9中的动态形式,angular,forms,reactive,reactive-forms,ngx-formly,Angular,Forms,Reactive,Reactive Forms,Ngx Formly,尝试实现:使用ngx formly/material根据用户选择的区域设置JSON实现动态表单。如何用我的对象数组“this.fields2”映射字段 在my component.ts中,我有: model: any = {}; options: FormlyFormOptions = {}; fields: FormlyFeildCongif[]; Fetching the JSON of the selected Locale: ngOnInit():void { this.la
model: any = {};
options: FormlyFormOptions = {};
fields: FormlyFeildCongif[];
Fetching the JSON of the selected Locale:
ngOnInit():void
{
this.langService.getSelectedLocaleData(this.cuurentLang).subscribe(
(res) =>
{
this.myDynamicForm = res.yBank.fields;
this.dynamicFormCreate(this.myDynamicForm);
});
}
public dynamicFormCreate(arr:any)
{
for(i=0; i< arrr.lenght; i++)
{
//here I am fetching data from json and creating an Object structure which is accepted by formly feilds
//the problem is how do I map this.fields2 array of objects with the formly feilds
this.fields2.push(
{
key: arr[i].type,
type: arr[i].type,
templateOptions:
{
label: arr[i].label,
placeHolder: arr[i].placeHolder,
description: arrp[i].description,
required: true
}
});
}
}
model:any={};
选项:FormlyFormOptions={};
字段:FormlyFeildCongif[];
正在获取所选区域设置的JSON:
ngOnInit():void
{
this.langService.getSelectedLocaleData(this.cuurentLang).subscribe(
(res)=>
{
this.myDynamicForm=res.yBank.fields;
this.dynamicFormCreate(this.myDynamicForm);
});
}
公共dynamicFormCreate(arr:any)
{
对于(i=0;i
my component.html
<form [formGroup]="myForm">
<formly-form
[model]="model
[fields]="fields"
[options]="options"
[form]="myForm">
</formly-form>
</form>
如果我正确理解了你的问题,那么你有几种方法来解决这个问题:
将字段2分配给字段
假设您的,this.fields2也是一个FormlyFieldConfig[],
只需将其分配到ngOnInit中的formly字段
在dynamicFormCreate方法中使用this.fields
或者您可以直接更新订阅中的this.fields(而不是使用fields2)
public dynamicFormCreate(arr:any)
{
对于(i=0;i
将JSON文件用于字段配置,只需从服务生成模型即可
在我最近工作的一个实现中,我在一个JSON文件中有字段定义,而模型来自一个服务,就像您的案例一样。formly库的力量来自于这种分离,它将通过将模型应用于表单配置来自动生成表单。我使用的是重复部分,我的配置JSON非常简单,而eas模型从后端获取多行,并对其进行形式化处理/渲染。
因此,除非您有一些非常复杂的呈现需求,而静态定义的配置JSON是不可行的,否则我建议使用选项3
ngOnInit() {
this.langService.getSelectedLocaleData(this.cuurentLang).subscribe(...);
this.fields = this.fields2;
public dynamicFormCreate(arr:any)
{
for(i=0; i< arrr.lenght; i++)
{
//here I am fetching data from json and creating an Object structure which is accepted by formly feilds
//the problem is how do I map this.fields2 array of objects with the formly feilds
this.fields.push(); // USING fields instead of fields2
...