In this blog, we will learn about custom form control, viable with template-driven and reactive forms, as well likewise with all underlying and custom structure validators.
In angular, we can make custom form controls by utilizing the ControlValueAccessor interface. And, we can likewise make a custom form control by utilizing @Input() decorator and make your structure dynamic.
Advantage of Property binding at the place of ControlValueAccessor
- If we are using controlValueAccessor to make form fields dynamic and for that, we need to implement a heavy-weight business logic but if we will do it by using property binding with the help of @Input() decorator then can reduce so many business logic.
- In ControlValueAccessor we need to write their 4 methods and also need to provide NG_VALUE_ACCESSOR to access the value of that control and changes.
- By using ControlValueAccessor we only get the value of that form field and we need to write validation logic separately but if we use property binding then we get value and validation both at the same time. So by using the property binding approach, we can reduce validation logic too.
- So the conclusion is that by using property binding at the place of ControlValueAccessor we can make our code lightweight and easier to make dynamic.
So here is an example of that
Here I am creating a custom control and binding that control with @input() decorator. Now in the parent component, I am going to create a reactive form and bind the control of this form.
So by using this method we can get that control in this form and it is very easy to create custom control without using ControlValueAccessor but by using controlValueAccessor it’s taking too much code and logic because it is an interface and if we use it then we have to use their methods too.
Creating Dynamic form with multiple custom controls:
Now let’s see how to create a dynamic form with multiple custom control and also add validation dynamically.
In the above code, we have created two form controls fullName and email. And added all validation dynamically to it. Also, we are passing labels, keys, values, and validations from the parent component to the child component which is custom form control.
Here we can see how we can bind it with a customs form control field
So by using this method we can get that control and validations in this form dynamically and it is very easy to create custom control without using
So, in this blog, we have gone through the introduction of customs controls. Next, we went through how we can create a custom control and added different validation in angular. To learn more about Custom control you can go through the official documentation here.
For more updates, please follow our LinkedIn page- FrontEnd Studio.
Thank you for sticking to the end. If you like the blog, please don’t forget to give a thumbs up and share it. Feel free to share your thoughts about this blog in the comment