Niral Sep,13 2017
Learn using Angular how to build a simple dynamic form that can be easily extended based on the requirement. We will create dynamic form component that will allow the user to provide configuration object and will render the form according to provided object and will expose the form submit event.
In Angular, there are two ways to build forms one is Template-driven and another is Model-driven.
Angular allows dynamic rendering capabilities. We can build a dynamic form and configuration driven form component using dynamic rendering capabilities, Let's see further now...
We will build a dynamic form component that will accept the form configuration object and will expose the form submit event.
We’ll capture the form configuration based on below interface:
We have considered only basic form controls like text, password, and date in this example.
type represents type of the input,
name represents name of the form control,
label represents label of the input, and so on.
Here is the file structure:
To use angular forms, we will have to import FormsModule and ReactiveFormsModule from the package
@angular/forms into our
Here is the DynamicFormModule:
Now that we have created
DynamicFormModule, we need to create one component that will take configuration object as an input and will create a form control using that configuration object, Here is the component for that:
DynamicFormControlComponent will not be used externally, we will be using it internally to add the form control
dynamically to the form. To add the form control dynamically to the form we will need the dynamic form component
that will accept the configuration object from the user and will create the form accordingly. Here is the code of
ViewContainerRef. We will use this to attach our dynamically created control components to the template.
ngOnChanges()with simple loop that goes through the
DynamicControlConfig (_formConfig)array, adding controls to the
FormGroup, and call the
buildControl()method is responsible for instantiating the
DynamicControlComponentand initializing its properties with
controlConfigobject and the
ngSubmitevent and emit a custom event named
formSubmitwith form data.
Now our component is ready to use, all we need to do is to import the DynamicFormModule into our AppModule, here is our AppModule:
We will use our dynamic form component inside AppComponent, here is AppComponent:
Here is the markup of AppComponent:
The output should looks a like below, I've used Bootstrap for styling.
When you hit the submit button it'll log the form data in browser console.
That's it, So it is easy to create a simple configuration-driven form, it can be extended to any level based on the requirements. You can add validators to the dynamic component, you can provide custom CSS classes to customize UI of the form, and many other things can be passed in the configuration object.
Happy coding, stay awesome!