使用JSON文件创建动态反应形式-Angular [英] Create dynamic reactive form using json file - Angular

查看:126
本文介绍了使用JSON文件创建动态反应形式-Angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用json文件创建动态反应形式,但没有与我合作.

这是json文件:

 "inputs":[
    {
      "formcontrol":"email",
      "validation":["required,email"]
    },
    {
      "formcontrol":"password",
      "validation":["required"]
    },
    {
      "formcontrol":"firstname",
      "validation":["required"]
    },
    {
      "formcontrol":"lastname",
      "validation":["required"]
    }
  ]

这是我尝试过的:

for(let input of inputs ) // json data
{
   this.t.push(this.formBuilder.group({
      input.formcontrol: ['', input.validation],
   }));
}

我知道我做的是不正确的,但是我不知道如何解决这个问题.

解决方案

您只需按照如下所述的formGroup动态添加formControl-

inputs =[
    {
      "formcontrol":"email",
      "validation":["required,email"]
    },
    ....
  ];

  constructor(private fb: FormBuilder) { }

  ngOnInit(){
    this.SignupForm = this.fb.group({});
    let control = new FormControl('');

    for(let input of this.inputs) {
      this.SignupForm.addControl(input.formcontrol, control);
    } 

    console.log(this.SignupForm.value);
  }

示例示例

如果需要,您可以在此处

查阅官方文档.

I'm tried to create dynamic reactive form using json file but didn't worked with me.

This the json file :

 "inputs":[
    {
      "formcontrol":"email",
      "validation":["required,email"]
    },
    {
      "formcontrol":"password",
      "validation":["required"]
    },
    {
      "formcontrol":"firstname",
      "validation":["required"]
    },
    {
      "formcontrol":"lastname",
      "validation":["required"]
    }
  ]

This what I tried :

for(let input of inputs ) // json data
{
   this.t.push(this.formBuilder.group({
      input.formcontrol: ['', input.validation],
   }));
}

I know what I did isn't correct but I have no clue how to solve this.

解决方案

You need to add only formControl dynamically as per the formGroup like below -

inputs =[
    {
      "formcontrol":"email",
      "validation":["required,email"]
    },
    ....
  ];

  constructor(private fb: FormBuilder) { }

  ngOnInit(){
    this.SignupForm = this.fb.group({});
    let control = new FormControl('');

    for(let input of this.inputs) {
      this.SignupForm.addControl(input.formcontrol, control);
    } 

    console.log(this.SignupForm.value);
  }

Working Example Snippet

If needed you may refer official Documentation here

这篇关于使用JSON文件创建动态反应形式-Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆