Create a form with input controls dynamically from JSON using Angular 2

£可爱£侵袭症+ 提交于 2019-12-06 10:09:49

Create dynamic form group and loop through the json and create respective element, where forms input type and its related attributes(like name, value, placeholder,type,required,pattern etc) were varying as per resource's attributes. So render the forms at run time.

Reference information

Creating forms in angular 2 using json schema at run time

You will need to import a FormBuilder from @angular/forms. Then create a FormGroup.

public form: FormGroup;

private _buildForm() {
  let obj = {};
  General['None'].forEach(val => {
    obj[val.fieldname] = new FormControl('', Validators.required);
  });

  _fb.group(obj);

}

On the template you will need loop through the form controls and and create the form based on the type.

This answer may not be give you all the answers you need but it's an eye opener on what you can do.

You may want to use FormArrays depending on how you'd want to implement.

Read through the angular2 documentation on forms. Also watch this video.

Angular 2 Forms | Kara Erickson - YouTube

Forms - ts - GUIDE - Angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!