Create a Dynamic Angular Form with ngx-formly

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 4 years ago

In our dynamic forms lessons we obviously didn’t account for all the various edge cases you might come across. Therefore if you need a more complex setup you might want to take a look at ngx-formly. Formly has been a very popular library even in AngularJS 1.x for rendering dynamic forms.

Ngx-formly is the Angular (2+) counterpart for doing this job. In this lesson we’ll quickly give it a look at how to transform our custom dynamic form rendering to use ngx-formly. For more use cases definitely check out this Configuration based reactive Angular Forms with ngx-formly collection and official ngx-formly repository on GitHub.

Instructor: [00:00] We have here our app dynamic form component, which takes here some configuration object, as you can see. This configuration object is described below here in the app component class. It describes basically a person object with some additional metadata, such as the label or valid errors, which are then interpreted by our app dynamic form.

[00:20] It then dynamically generates this kind of form here, using the Reactor forms approach in Angular. Our example implements a very basic rendering of such a dynamic form. We implemented not all of the available validators and we definitely did not cover all of the different kinds of edge cases you may come across when you are in a real-world application.

[00:40] Therefore, you definitely want to use some library which already implements that. One library which does so is ng-formly. Now we are going to take a look on how we could use ng-formly to basically convert our custom dynamic form into one that can be rendered with ng-formly itself.

[00:57] The first step is to install it. It comes with two packages. This is the core library, basically, and then they have different kind of libraries, depending on the font and framework you're using. Right now, they're supporting Bootstrap and also Angular material. Let's go with Bootstrap for now.

[01:13] The next step is to go into the app module and install here the different kind of models we have just installed. First of all, we need the formly module, which comes from formly/core, and then the formly Bootstrap module, which comes from the Bootstrap library here. Then we need to, obviously, also also register them. We use the formly module.forRoot, and the FormlyBootstrapModule.

[01:37] Next, let's go into the app component. We obviously need to adjust this API, such that it matches the one formly requires. First of all, formly distinguishes between the data object and the actual configuration of the fields in the form. We have mixed them up. As you can see here, we have the value, as well as some metadata on how the form should render.

[01:57] Let's first split that out. Let's call it a person object here. We have first name. Let's leave it with these properties. Let's rename this to personFields. These person fields in formly are basically a formly field config object. It takes an array, where, inside, there are the different kind of objects.

[02:20] Let's first take a look here on how we need to transform here our first name. First of all, we have an object inside that array. Let's remove that property here. Then we need to specify where this configuration belongs. The key here indicates that property name on our data object, so that will be the configuration for that first in part here.

[02:44] Next, we have here the input type, where it defined directly the input type of the html control and not the different kind of type text, type radio, and so on. Those kind of things are defined inside the template options, so is also the label, so let's move it inside here.

[03:03] We can remove the value, because the value's already specified here on top in our data object. Then we need to specify the validators. Inside here, you have a validation property, and you can assign the validators director from the Angular forms module. We can remove this one.

[03:21] What is still missing is the validation messages. The validation part here takes a messages property, where we can simply put name of our validator and the according message. What's also important here is that you could simply take the validator's compose method to combine multiple validators inside here. But, for our example, we won't need that right now.

[03:46] In order to not bore you too much, let me simply copy in the configuration for the remaining properties here. Let's quickly have a look of what we copied in here. For the age property, we have still an input type here on the html part, but the specific type of html tag is then of type number, because we want a number input field.

[04:07] The validators are exactly the same, just that this time we used the min validator. What's maybe also interesting here is how the radio button list is being done. Here we have a radio button, so a type radio, for the HTML part, and then we have the options inside here, which specify the different kind of values the user can choose. Great.

[04:29] We need to now adjust here how the data is passed inside our dynamic component. First of all, we will have to add another input property which will pass in the data object, which is now person. Here, instead, we reference the person fields, as that is the one which holds our configuration.

[04:45] Let's jump into the dynamic form component. Let's, first of all here, add the new input fields. We have a new input, data, which will hold our person object. We can here delete most of these parts, as we won't need them anymore, because formly takes care of them. Similarly, if we scroll up here to our HTML part, we can drop out the whole rendering story.

[05:08] What we need to do here is initialize a new form group. The binding can still remain the same. The only thing we need to modify is, inside here, we need to specify the formly form component. We need to pass in the model, which, in our case, is actually the person, the data property, which we pass from the outside.

[05:28] Then we need to pass in the configuration, which is the form data object. Finally, we can also here add a button, which is of type submit, which will then read a response before submitting the entire form. With that, we have concluded the initial configuration of formly. Great.

[05:44] Let's correct here quickly our typo, and then let's start up our development server again. Once it is up and running, let's refresh our form. You can now see that the form gets re-rendered. It is not exactly identical as we have designed it before, because we would have to add some styling.

[06:01] Let's also add here ng-submit. We can simply say submitted data equals data. That is a property which we define quickly inside our component here. We can then render it here on our form, and that data property is basically just a model that formly gives us. If we save that again, and we save here, we can see how the data basically gets submitted correctly, and it also data-binds.

[06:29] Also, the validators work just as expected. If we remove the value, we get the validation error. If we write in again, it disappears. Also the min validator on the number field works just as expect.

Jerome
Jerome
~ 6 years ago

This is an awesome course on getting your head around taking advantage of dynamic form generations. Thank you Juri. My only worry about using ngx-formly is adding another level of abstraction on top of it and losing some of the customization capabilties. Any concerns about that?

Juri Strumpflohner
Juri Strumpflohnerinstructor
~ 6 years ago

hey Jerome. totally understand what you mean. for simple things you can definitely roll your own form generation mechanism as I've sown in this course. For more complex things however I tend to ngx-formly. This video here just gives a very rough overview. Actually just this week I started to dive deeper into ngx-formly as I'm evalualing to use it more heavily in one of our projects. That said, it's really powerful what I've seen so far. I'll know more however in the next couple of weeks. In case connect with me on Twitter. pretty sure I will post some stuff there, some blog articles & maybe even some in-deep egghead lessons ;)

Jerome
Jerome
~ 6 years ago

Thank you for the quick reply. I really appreciate the feedback. I have a very specific case for a client/project I am working on right now where I thought your lesson would be a perfect match until... I have to handle cascading logic between various elements of a dynamic forms, meaning cascading lists, displaying fields and/or data based on previous selections. Overall, business logic mixed with dynamic forms... which does not seem to be easy. From your experience, should I try ngx-formly or try to roll my own? Thanks again for a great and concise course. Cheers.

Juri Strumpflohner
Juri Strumpflohnerinstructor
~ 6 years ago

I'd give ngx-formly a go. Like experiment with it for half a day or day to see how far you come to prototype your use case. As said, I'm currently doing exactly the same, to see whether it's flexible enough. And so far I'm quite satisfied tbh.

Michael
Michael
~ 5 years ago

Juri, any chance you'll do a course on the latest ngx-formly version ?

Juri Strumpflohner
Juri Strumpflohnerinstructor
~ 5 years ago

@Michael Hey, yes, it's been in the planning for a while and my goal is to release it in the next 2 months. It'll be probably a custom playlist on Egghead here (just as this one: https://egghead.io/playlists/build-performant-and-progressive-angular-applications-78032ff5). Just keep an eye around here. I'll also announce it on my Twitter (https://twitter.com/juristr) or on my tech news (https://juristr.com/newsletter).

Stay tuned 💪

Michael
Michael
~ 5 years ago

Fantastic !!!

JMONER
JMONER
~ 4 years ago

Hi, is it possible to add more then one Validators? For example a required and a pattern...

Juri Strumpflohner
Juri Strumpflohnerinstructor
~ 4 years ago

@JMONER sorry for the late reply 🙏. Of course you can. I actually created an entire series on Formly for Egghead which you can find here: https://egghead.io/playlists/configuration-based-reactive-angular-forms-with-ngx-formly-465f

You can also read about validations on the official formly docs: https://formly.dev/examples/validation/built-in-validations

~ 2 years ago

Great job @Juri Strumpflohner. Now I can take the Frmly course with a basic knowledge of what is going "under the hood"!

Markdown supported.
Become a member to join the discussionEnroll Today