angular-formly: Extending Types

Kent C. Dodds
InstructorKent C. Dodds

Share this video with your friends

Send Tweet
Published 8 years ago
Updated 4 years ago

Extending types is one of the ways that makes angular-formly help you keep your Angular forms DRY. When use responsibly, they can make it much easier to manage common types, allowing you to add a bit of functionality to a common type.

[00:00] Angular-formly allows you to extend existing types. We have a list of Avengers here. We can choose our favorite. I'll say, "Captain America." That will set our favorite Avenger. Everything is working as we would expect.

[00:11] Let's say that we wanted to use this avengerSelect in many places throughout our application. We wouldn't want to have to copy these options everywhere. We're going to create an avengerSelect type that will extend the select type.

[00:24] This will happen inside of our run phase. We'll say, "function FormlyConfig," and then we'll simply say, "FormlyConfig.setType." Our type name will be "avengerSelect." This will extend select.

[00:49] Now we can specify some default options. We'll go ahead and copy all of these inside of our default options. Instead of select here, we're going to use avengerSelect. Now everything else works as expected.

[01:11] We've moved all of our common configuration inside of this avengerSelect. Everything works exactly as it did before, but now we can use this throughout our application just by saying the type is avengerSelect.

[01:29] Obviously, this will be a favorite Avenger too. They won't be bound directly to the same model in that case. Also, you can override these default options as well, by simply specifying the option. We'll say, "templateOptions with label favorite", we'll say, "Second Favorite.'"

[01:52] You can override these different options as well. This makes your code a lot more dry and quite readable as well. You simply say, "The type is avengerSelect." I know exactly what that's going to look like. I know the options that it's going to have.

[02:05] That is how you extend types using angular-formly. Inside of your run phase, you inject the FormlyConfig, and then you set the type. You give it a name, and then this key there is the extends select.