Reactive Forms - The Basics

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] today I'm going to show you everything you need to know to start using reactive forms in angular 6 effectively we'll do this by building five different forms that started the absolute basics then progress on to topics like dynamic form fields validation and submitting your form data to a back-end database almost all apps use forms in some capacity so understanding reactive forms is a very valuable skill to have as an angular developer if you're new make sure to subscribe and grab the source code from angular firebase comm and I'll be giving away three free hats on Friday all you have to do is leave a comment on this video I'll be starting off here from an angular 6 project and the first thing I'll do is add angular material to this project because it has some awesome UI elements for form validation you can install it in your project by running ng add angular slash material then I've already generated five different components that I'm going to use to demonstrate these different reactive form examples if you don't know how to generate components with the CLI make sure to watch episode 104 from last week the reactive forms module isn't included by default so we're going to import that from angular forms and then we have a bunch of modules that were importing from angular material that handled different form fields that we want to use then all of these modules will be added down to the import section giving us access to these various components and services when it comes to angular material there's a whole bunch of different form elements that you can use so make sure to check out the docs and experiment with some of the examples there the first reactive form we'll build starts with the absolute basics let's see how we can set up a few form controls for an email a message and a select field for a career then we'll observe the changes to the actual values being entered into this form you'll notice that every time we enter something into this form it updates the value object that's because under the hood the form is using rxjs to treat the form as a reactive real-time stream let's go ahead and jump into the type script for this component and we'll take a look at what we need to build the reactive form there's really two things you need to know to get started and that's form group and form builder form group is the actual class that we use to tie different form controls together into a single unified form form builder is just a service that we can use to make building forms easier so the first thing you'll deal with pretty much any reactive form is to clear the variable type to the form group and we'll do this in every single one of the demos the next thing we'll do is add the form builder service to the constructor of this component then we'll create a data model for this form during ng on an it you can think of this as a schema for the data that holds the actual values and validation rules for the fields inside your form we call form builder group and then we set email and then we can provide an empty string which defines the default value most forms will start off empty but if you want to set a default value you can just define it here and that's really all it takes to build a reactive form in the typescript but you might also want to extract the data from this form and the typescript as well the form group has a method on it called value changes that returns an observable if we subscribe to that observable it's going to emit the value of the form every time it changes that's how it was able to console.log every value change in the demo now we need to connect this form group to the HTML and bind it with our angular material UI components for every reactive form you'll bind this form group attribute to the form you defined in the type script and if you want to see the value of the form in the HTML you can just call a my form value and then use that JSON pipe from there we'll add a material form field and an HTML input with the matte input directive so that's just plain angular material to connect it to the reactive form we call a form control name and give it the name of the attribute that we defined in the type script we can go ahead and follow the same pattern for all of the other fields in our form and again the only special thing we need to do is call form control name everything else is just a plain angular material form the one thing you might notice about forms is that there's a lot of markup code that you have to deal with to avoid leaving you at the big bowl of code soup I want to start looking at ways we can keep our reactive forms dry very early on the second demo we'll look at is a nested form what's special about this form is that we have a parent form group and then we have a couple of nested forms inside of it for each of these phone numbers for the form bow you can see that we have a nested object inside the forum for each of these phone numbers let's take a look at how we can use nesting to keep our forms organized we have the same setup as our previous basic form but this time we'll create a reusable form group that we can use multiple times in the parent form again we call form builder group and then we'll add a couple of default values here for the various parts of the phone number then we'll define the parent in the same way by calling form builder group we can nest the schema that we defined for phone numbers multiple times within this form so maybe we have a home phone number and also a cell phone number then if we switch over the HTML the initial markup is exactly the same but there's one key difference when dealing with a nested group instead of using form control name we'll set up a div and pass it the form control group name this will be our cell phone group then inside the context of cell phone we can start adding our inputs which will take the form control name so we can control the cell phone that way and then we can do the same thing for the home phone as well so that works okay if you have two phone numbers but what if the user can dynamically add as many phone numbers as they want using this nested form technique with ten phone numbers wouldn't be maintainable at all in the next demo we're going to look at form array which allows us to dynamically add fields to the form instead of hard-coding in the form markup we'll just add a button here that allows the user to add as many phone numbers as they want and it will add a new field for each one to our reactive form you'll notice that instead of a nested object we now have a nested array of objects and because every element in an array has an index we can allow the user to delete any phone numbers that they've already added to the form the initial form setup is very similar but we also need to import form array from angular forms from there we can set up a phone's property on the form and instead of making this a nested form it'll be a form array that just starts out with an empty array then the next thing we want to do is set up a getter to retrieve the phones from the form this is technically optional but getters will make your life a lot easier when working with reactive forms as we'll see here in the upcoming demos we can have this method return the phones from the form and we'll make sure to return that as a form array then the next thing we need to do is set up a function that will run every time a button is clicked to add a new field to the form let's call this the add phone method and we'll first set up a variable that defines our form builder group then we can use the getter to return the form array from the reactive form and we'll call push on it with this new form group that handles adding a form group deleting a form field is even easier when we loop over them we'll be able to get the index then we can simply call form array remove at this index and that removes it from the reactive form the HTML markup is going to start out exactly the same as before but now that we have an array we're going to call form array name with that phone's property then because we're dealing with an array we're going to need to loop over it so I'll say let phone of phone forms controls and while performing this loop we also want to keep track of the index which we can do with let I equals index now each item in this loop is going to be a form group so we need to pass the form group name which is just the index when dealing with a form Group array now we can set up the form fields just like we've done in all the previous examples passing at the form control name the main difference is that we now need to populate this array with some items which we'll do on a button click so we can set up a material button down here then we'll run our ad phone event handler when this button is clicked so that button lives outside of the loop but then to delete an item we want to go back inside of our for loop and add the delete method to a button as well so make sure you're inside of ng 4 and then add your button inside of there and this time bind it to the delete phone method and pass it the index as an argument now we know how to build large dynamic forms but we're going to need to validate the user input into these forms the one thing I haven't shown you yet is that the reactive form has a whole bunch of different states that it can be in for example it can be valid if it is passing all validation rules it's considered dirty if the user has typed into it it's considered touched if the user has entered a form field and then left it and all of these different states can be applied to the entire form group as a whole or they can be used for each individual control inside of the form and angular will apply a CSS class for each one of these states to the form so you can use it to control the styling based on the state that the form is in fortunately angular material does most of this for us right out of the box as you can see here if we don't apply a ballot email it's going to give us this message that says your email does not look right but as soon as we enter a valid email that error message goes away we can also show different messages based on the type of error that's received for example we might say five is too young to use this app while 99 is too old to use this app and then you'll also notice that we have a submit button down here at the bottom that buttons disabled until the form is completely valid that's a very important technique because it often prevents the user from submitting bad data to your back-end database let's go into the typescript and we'll import validators from angular forms angular comes with a bunch of built-in validators that will cover 90% of your validation use cases for each form property we'll set up the default value and then as the second item in that array we'll pass another array with a series of validators I'd like to point out that you can pass in another array after this with asynchronous validators but that's a topic for another video for right now we just want to synchronously validate that our email is required and that it's a proper email format then we also want to validate that our passwords required and we can also pass in a regular expression here to make sure that that password meets a certain requirement for example we want to have at least one letter and one number in the password string then when validating numeric values we can look at the minimum and maximum value which we can use to set up an age range for the validation it shouldn't be confused with min length min length is for Strings that will validate how long a string is or how many characters are in that string for numeric values you want to use min and Max so we'll say the minimum age is 18 and the maximum age is 65 and we also have a checkbox in this form so if we want to verify that that checkbox is checked we can validate that it is required and the value is true now a quick pro tip when working with validations is that you want to set up a whole bunch of getter for the various fields in your form this will just make your HTML way cleaner as you're setting up logic in there to show different error messages for different fields now if we jump over to the HTML we can use the material error component along with ngf to conditionally show error messages because we set up that getter we can just say ng if email is invalid and if the email has been touched then we want to show this error message in other words if the user tried to enter an email and it wasn't correct we want to notify them that they need to correct that then another cool thing we can do with angular material is show hints for more complex values for example for our password we want to give them a hint that it requires one letter and one number then if they still enter it wrong we can say your password sucks with a validation error so that's pretty cool for just showing error messages when we know the entire form value is incorrect but we have multiple validators for our age field so we might want to show a different error message based on the type of validation error for example we have a minimum age error and if we get that error we want to show a different error message than if it's the max age so if the user enters an age that's less than 18 then we're going to show this message that says your actual age is too young to use this app then we can follow the exact same process for the max age here but just change some of the details if you have a ton of error messages like this you might want to map them to an object in the typescript one of the nice things about reactive forms is that you can handle some of the logic in the HTML and some of the logic in the typescript depending on your use case then the last thing we'll look at is how to disable the submit button for that we can simply bind the disabled attribute to the form invalid state on the reactive form so that's super easy and something you'll probably do on every single reactive form that you build we finally reached the fifth and final demo which is how to submit a form to a back-end database and naturally we'll use cloud firestore to do that so let's take everything we've learned and just build a simple contact form like you would find on any web site we will validate it and then after we know it's been saved in the database we'll show a success message saying that we your submission if we go into the firebase console we should be able to see the data that we entered in the reactive form saved to our back-end database this next section assumes that you have angularfire 2 installed along with a firebase project but you can follow the same principles for any back-end so we have a basic reactive form following the principles that we've already covered what we'll do now is import our angular firestore database as well as the tap and first operators from rxjs the form submission is asynchronous so we're gonna have a couple of different state items here loading and success which will both start off as false the next thing we need to do is create an event handler for when the form is submitted this method will be triggered when the user clicks the submit button on the form the first thing we'll do is set the loading state to true then we'll grab the current value from the reactive form and we do that by calling my form value then I will set up a try-catch block here so we can catch any errors that might have occurred on the back end and then we'll await the angular firestore collection which we'll call contacts to add this form value to the database after we've awaited that operation to happen successfully then we'll set the success state to true but if there's any errors then we'll just go ahead and log those to the console then after that happens we'll set the loading state back to false then there's really not a whole lot we need to change to the markup we want to hide the form once it's been successfully submitted which we can do by binding the hidden attribute to the success state but the most important part is that we listen to this in GC then run our submit handler method which will send the data to the database then as a final touch down here at the bottom will add a success notification that lets the viewer know that their data has been saved in the backend so hopefully that gives you a good tool set to build full stack reactive forms in angular 6 I'm gonna go ahead and wrap things up there if this video helped you please like and subscribe and if you're ready to build more advanced features with angular forms and firebase consider becoming a pro member at angular firebase comm go get access to new pro videos every week plus a whole support network designed to help you get your app into production faster thanks for watching and I'll talk to you soon
Info
Channel: Fireship
Views: 185,543
Rating: 4.9295368 out of 5
Keywords: angular 6, firestore, web development, reactive forms, reative forms angular 6, angular forms tutorial, angular forms basics, rxjs, formgroup, formbuilder, html forms, ng6, angular material, angular material forms
Id: JeeUY6WaXiA
Channel Id: undefined
Length: 15min 48sec (948 seconds)
Published: Tue May 22 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.