Creating forms in angular 2 using json schema at run time

Posted By : Prashank Jauhari | 28-Nov-2017

Creating forms in angular 2 using json schema at run time.

 

During our project we faced a requirment where forms input type and its related attributes(like name,v alue,placeho lder,type,requ ired,pattern etc) were varying as per resource's attributes. So we needed to render the forms at run time. Though there are plugin available that will do it for you, but in this blog i will be explaining custom implementation.I will be working on basic but dynamic signup form.

 

Step 1: Create the Json Schema that will act as the skeleton for yout Dynamic form.

 

Example Json is as under:

 

 

Step 2: Create a signupComponent with a private inputField variable that will contain the schema for your form.

step3: create signup component html ,and its css file(it is optional),

 

And bind the attributes of input html tag with our input object of inputField json array. Notice that we perform two way databinding for value property of input html tag, this is done to get Entered value when user submit the form.

 

Notice the submit button its click event is bind to our send() function inside our signupComponent.ts file.

 

When we open your app in browser we can see Dynamic form created as per our json schema.

 

 

Whenever user enters the value inside dynamic form and submit the form we can get its value from binded object, as done inside the send function of signupcomponent.ts file as shown in the below image. Please refer the console logs to see the result.

 

When ever we change the json schema our form structure also get changed. Form Example adding a new field json metadata in the jsonshema array will be reflected in the created form.

 

New Json object :

{type:'date',name:'DOB',value:'',placeholder:'yyyy/dd/mm',required:true}

 

 

 

New Displayed form is as under:

 

Note: You can add your own functionality as it is custom implementation and you are not relying on plugin......

 

 

 

 

 

 

 

 

 

 

About Author

Author Image
Prashank Jauhari

Prashank is quick learner and passionate about new technologies. He is currently working as Java Developer with knowledge of Spring and Hibernate.

Request for Proposal

Name is required

Comment is required

Sending message..