The article provides a comprehensive guide on enhancing JSON-powered forms in Angular applications using ngx-formly, covering advanced features such as validations, repeatable sections, conditional fields, form reset, and submission to an API.
Abstract
The second part of the "JSON Powered Forms in Angular" series, this article delves into advanced form functionalities using ngx-formly within an Angular project. It outlines how to implement basic and custom validations, create repeatable form sections, introduce conditional field visibility, reset form data, and submit form data to an API endpoint. The tutorial emphasizes the ease of integrating these features to build robust, dynamic forms suitable for enterprise-grade applications. It also provides practical examples and references to an example project on GitHub, ensuring readers can follow along and apply the concepts to their own Angular forms.
Opinions
The author believes ngx-formly is a powerful tool for building complex forms in Angular, suitable for professional, enterprise-grade applications.
Custom validation is highlighted as a flexible feature, allowing developers to create both the validation logic and message presentation.
The repeatable sections feature is praised for its utility in applications where such functionality is required.
Conditional fields are presented as an essential feature for large Angular applications, simplifying the form's dynamic nature based on user input.
The author assures readers that ngx-formly can be used to automatically generate forms based on models and the Open API spec 3.0, showcasing its versatility and integration capabilities.
Encouragement is given to readers to engage with the author through comments or direct messages on Twitter for further assistance or clarification on form setup.
How to Build Fast, Advanced JSON-Powered Forms on Angular With ngx-formly
Validations, repeatable sections, conditional fields, and submitting your form to your API
This article is the second installment of a two-part series called “JSON Powered Forms in Angular.” If you didn't check the first part, I recommend doing that first.
In the first article, I discussed how you can implement ngx-formly in your Angular project with the UI framework Angular Material.
We are going to continue with the same project in this article. We will implement basic validation, custom validation, repeatable sections, conditional fields, how you can reset your form, and how you can submit the form to an API endpoint.
Sit back and get yourself some drinks because we are going to dive into the rabbit hole of advanced forms with ngx-formly in Angular.
Part 1
1. What’s Ngx Formly?
2. Install Dependencies
3. Set Up an Angular Project
4. Add Ngx Formly and Your UI Framework
5. Create a Simple Form
6. Check the Data From the Form
Part 2
1. Validation
2. Repeating Sections
3. Conditional Fields
4. Reset Form
5. Submit Form
1. Validation
Let's start with validation. Every form should have some validation to help its users fill in the correct information.
Adding basic validation is super easy by only adding some properties to the object. If you want to have custom validation, you only have to create two functions and add them to the formly module.
1.1 Basic validation
There are a few validations you can add by only adding properties to the input objects.
required: If a field is required.
min: This is only for the number input field to define a minimum number.
max: This is only for the number input field to define a maximum number.
minlength: With this property, you can define the minimum amount of characters.
maxlength: With this property, you can define the maximum amount of characters.
In every input object, you can add those properties. If you don't add the field, it won't be validated.
If you want to have a validation message for the required property, you have to add it in the angular.module.ts.
With the parameter field, you can get access to the values that have been filled into the validation properties. This will help to make it more dynamic.
If you want to have custom validation for your field, you need to add two functions. One function (IpValidator) does the validation and another (IpValidatorMessage) function handles the validation message. Those functions need to be included in FormlyModule.
In the FormModule.forRoot(), you give a config object. For the validation function, you add the property validators in which you add an array with one object ({ name: 'ip', validation: IpValidator }). To add the validation message, you add the property validationMessages in which you add an array with an object ({ name: 'ip', message: IpValidatorMessage }) like this.
Your app.module.ts should look something like this:
In the field config of the field you want to have the custom validation, you have to add the property validators that includes a validation property with a value ["ip"]. This value is the same as you have added in the app.module.ts.
Not all the applications would need this. But when you need it, this feature becomes very handy.
You can group an array of fields to make them repeatable. But first, we have to create a new formly type (RepeatTypeComponent) that includes a <formly-field> and a button for creating a new group of input types.
We have to add this formly type to the declaration property and FormlyModule so we can use it in our form configuration.
Now we are able to add it to our form config array.
If you output your model in <pre>{{model | json }}</pre>, click on the + button and fill in the input fields. Now you will see that there is an array with all the information.
If you're building a big application with Angular, you probably need conditional fields. With formly, we can do that in a very easy way.
You only have to add a hideExpression property to your field config. The value will refer to the model. If the previous input name is empty, the email field will be hidden. When it contains a value, it will be shown.
The great thing about this is that the email property is also not visible in the model, so you won’t send it.
With formly, it is also very easy to add a reset button to clear all the values in the form.
Just add the buttons, create an options property in the component class with the type FormlyFormOptions and add the button to the form. Then add [options]=”options” to the form component and (click)=”options.resetModel()” to the button.
It’s important to know that if your model is already filled with values, this functionality won’t delete that information. When you change the value or add a new one, it will reset the values.
Submitting our forms is also very easy with formly.
Add to your <form> tag a (ngSubmit)=“submit()”, which will call a method to submit that should be declared in that component.
onSubmit() {
if (this.form.valid) {
console.log(JSON.stringify(this.model));
}
}
Right now, this will show the model data in the console. But I guess if you are using Angular, you are familiar with how to send requests in it. If not, please use this example.
Make sure that you have loaded the HttpClientModule in your app.module.ts.
In your component, make sure you include the HttpClient in the constructor, which will make sure you can use this .http in your component.
constructor(private http: HttpClient){ }
In the submit method, we are going to use the HttpClient to do a post request.
We know that this URL is not valid, so it will result in an error. But if you replace it with a valid one, it will work.
It is better to do the request via an Angular service off-course, but I’ll leave that to you.
I hope that this second part of the tutorial helped you to build more advanced forms with ngx-formly. If you still have questions on how to do certain things, please add them to the comments.
Are you still unsure of whether ngx-formly is valid for enterprise-grade applications? I can assure you that my team and I use it ourselves to build all the forms with more than one input field.
We even made it so generic with our API based on the Open API spec 3.0. For every model, it builds the form automatically.
After reading this story, I hope you learned something new or are inspired to create something new! 🤗
If I left you with questions or something to say as a response, scroll down and type me a message. Please send me a DM on Twitter @DevByRayRay when you want to keep it private. My DM’s are always open 😁