Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
  • Overview
  • Transcript

1.2 How to Code Forms in Angular 2

In this lesson, we’ll work through a complete example of how to code forms in Angular 2. We’ll create a form component that can display and edit information. Follow along and I’ll show you how to use the essential features of two-way data binding and input validation.

Code Snippet

This Angular 2 template snippet creates an input field. The value of the input field is two-way connected with the model.name field defined in the corresponding .component.ts file. The name of the input field is "name". And finally, a reference is created to the field as nameField, which can be referred to elsewhere in the template. The nameField ref is used below the input field, to show or hide a <div>, depending on the state of the input field.

    <input type="text"  id="name" required [(ngModel)]="model.name" name="name" #nameField="ngModel">
    <div [hidden]="nameField.valid || nameField.pristine">
        Name is required

Related Links

1.How to Code Forms in Angular 2
2 lessons, 11:47

Free Lesson

How to Code Forms in Angular 2

1.2 How to Code Forms in Angular 2

[MUSIC] Hello everyone, I am Reggie Dawson. Welcome to the Angular 2 forms coffee break course for Tuts+. The Angular platform has always been known for how it handles data. Instead of all the code necessary to display this data with standard JavaScript, Angular makes displaying and manipulating this data simple. This capability extends to how Angular handles form data. With the minimal amount of code we can create dynamic forms to in order display our data. The new thing about Angular 2 forms that our information can flow both ways. In order to better understand this, let's set up a sample project. The quickest way to set up an Angular 2 project is to use the Angular command line interface. After installing this tool through npm, we can navigate to the folder where we wanna store our project. All we have to do then is use the NG new command to generate our project. The full syntax of the command has the name of the project. When we run this command, it will generate a folder for us with this name to contain our project. After that, all the preliminary setup of our project is done and we can start to add our form. Now this form will exist as a component that we will place in the template of another component. This serves the purpose of making the form portable. We can add it to any component in our app, and we can even use the same component in another app. The first thing we need to do is create a folder named Form in the app folder of our project. In Angular 2 we built our project in the app folder. I typically like to keep my components in their own separate folders, but this is a personal preference and not required. After that create a file called dev.ts in this folder. Now this file will not be a component or module, but instead will be a class to represent the data in our app. We're using TypeScript for our app, and this allows us to use classes. The first thing we do is add our class using the export keyword. This will allow use to import this class into our form component, then we add our constructor. Inside the constructor we'll add our properties. First we have our name property that is set to a string. This is an example of the typing that gives TypeScript its name. Then we add the language property, which is also set to a string. Then the final property is the exp property, which is set to a number. Now you also may notice that I've added a question mark to this property, but the first two properties didn't use this. The question mark indicates that this is an optional property. One thing of note to take into consideration, is that a required property cannot come before an optional property. After that our dev.ts file is finished. Next create a file called form.component.ts in the form folder. We need to import components so that we have access to the component decorator. Then we import the dev.ts file that we just created. Then we add our component decorator to configure our component. First we have our selector, which is how we will add our form to other templates. The template URL points to an external HTML file, and the styles URL points to an external CSS file. Then we add our class with the export keyword again. The first thing we add to our class is an array. The form we are going to build will be used to sign up developers to our site. As you know from our class we built for our developers, the language property is required. We will use this array to choose a language for our developers from a list. Next we add our model. This represents the particular set of data that we are dealing with, in this case, the current developer. Instead of our form starting with empty values, here we use our dev class to create an instance of this class. We set any developer as the name to provide as a prompt to enter a name. Then we set the language to choose a language from our array. Finally we set the years of experience to zero. These values are starting values to give the end user some guidance as to what information they should put in. This also means that we can select choose a language as the language option, but in the real app we will make sure that they can not this option. We will talk more about the model in a moment. Then we have the submitted variables set to false. We will use this to display the correct form based on whether or not we have submitted data. Then the on submit method will change the submitted property to true, when we submit our form. You will see what this change does in a moment. Then finally we have our new Dev method that will reset our form if we wanna add a different developer. This will essentially clear out any information that we have entered so far, and let's us start over. After that our form component is done. Next create a file called form.component.html. Now although this is an Angular 2 form, most of the magic will happen in the HTML template. The first thing we will add is a div in our title. This div uses Angular 2 property binding, which is why hidden is wrapped in brackets. This is one way binding, which means it flows from our component to our target element. In this case, the form will be hidden if the expression evaluates true. Remember when we set the submitted variable to false? This means this div will show when our form starts. Next we have our form tag, added to our tag, we first have an event handler bound to ngsubmit. Angular 2 event binding is specified by wrapping the event in parenthesis. This cause the on submit method that we know sets the submitted property to true. We now know that this will cause the form to disappear. But how will we get the data from our form? This starts with the pound sign dev form in the form tag. The pound sign indicates that this is a template variable. This allows us to wrap up our form data in this variable for access. It is also how we apply the directives that Angular 2 provides us with forms. Which is why we add the NG form to our variable. Next we had a div that will be used to display the contents our inputs. This is not necessary, and I only added this so that you can see the data that's in our model. We're using interpolation to display the properties of our model. When our app is first run, this should display the properties that we initial set in our component. Next we add our first input for the developer's name. This is a standard HTML text input. Required is a standard HTML attribute that specifies this has to be filled out before we could submit the form. We already know that this is a required property. But we are also going to use this to provide some visual cues when the user is entering incorrect information into the input. Next we have ngModel which is wrapped in square brackets and parenthesis. This indicates that this is using two-way data binding. This means data will flow both from the template to the component and vice-versa. NgModels are directive of Angular 2,and behind data binding, it also allows to track the validity of our data and our inputs and across the whole forum. Here we're applying this directive to our models name property. Which will allow us to track its state. Next we have a name property which is required when using ngModel in a form tag. Then finally we have a template variable attached to ngModel. This is here so that we can track the state of our input. We have options as to how we can provide visual cues to a problem with the input. We can change the color, such as turning the color of the border of our input red. Or we can display a div when there's a problem. I'll actually do a little bit of both. Right after I input, I've added another div down to the hidden attribute. This time we are checking if the input is either valid or pristine. Valid is when the input is not empty. Pristine indicates when the input has been changed. In either of these instances, the div will be hidden. ngModel tracks changes to the control and dynamically applies CSS classes. We can then use these classes to apply styling depending on the state of the control. Next I've added the text input for experience. Since this is not a required property, we don't need the required attribute or the template variable. Again we had the ngModel or name, which of course is the required. Then finally instead of an input we have a html select for our language. Remember we added in an array with our languages, so here we'll just display a list that the user can choose from. Now even though this is also required, we will not display a div this time, and just show a visible cue. It won't make a difference, since if this information is invalid, the submit button will not work. Also again in the real app, we will make sure the user could not submit choose a language as the language. Inside the option for select we have the ng for directive. This directive displays the contents of an array as a list, speeding up a duplicate template for each option. Let laying of language is assigning one item from the array on each pass in the lang variable. After that we bind the value of the option to the language variable. Once we do that, whatever we select from the list will be set as our language. The lang in curly brackets will display the selected language through interpolation. Then we have our submit and reset buttons. The submit button works with the ng submit we have on our form tag, and sends the form data when clicked. We also had the disabled property bound to the div form invalid. Remember when we added the div form template into the form tag, this allows us to track the validity of the entire form, and make sure that proper content is entered in each control. If not the submit button will not work. Then the reset button runs the New Dev method that we know clears out our model, so that we can add a different developer. devForm.reset serves to reset the state of our controls so that they display correctly, depending on the state they are in. Now once we click on submit, we know the submitted value will be set to true, which will hide our form. When the form is hidden, we will just display the results. To do this we simply add another div in the head with the attribute. But this one will display when the submitted variables are set to true. After that we have our properties of our model to be displayed through interpolation, just like in our form. Finally, we have an edit button that is bound to a click event handler. Instead of calling a method, however, this just sets the submitted variable back to false. This has the effect of returning us to the form, so that we can edit the developer further. Next create a file called form.component.css. In this file we will add one CSS rule that will change the outline to our controls to red using the ng-invalid class. As I mentioned, Angular dynamically applies classes as the controls are changed, and once the controls lack any data, this class will be applied. Now the last thing we need to do is add our form to our project. Let's go to the app.module.ts. Now since our app was generated by the Angular command line interface, we already have the forms module. But if you don't, you'll need to import it manually to use all of the Angular features we added to the form. After that we have to import the form component into our app. And then we add it to our declarations. Finally, let's go over to the app.component.html file. This is the template of the module that our app will display first. Here we will add the selector for our form component, and just like that our component is now part of the AppComponent. Go ahead and save your file and navigate to its folder in the command line. Once you do that, run npm start so that we can preview our project. Once the project is compiled, navigate to local host colon 4200 in your browser. Now if we type in the name, you can see it update as we type. Now if we click on Submit, it just displays our data. Clicking Edit should take us back to the form. Now let's remove the name all of the way. As you can see, the border turned red and the div displayed saying name is required. Also the submit button is grayed out indicating that it is disabled. Then finally if we click on New Div, the form should clear and now both the name and language should be outlined in red. And of course, all of the properties are empty. You should now know how to make use of forms in your Angular 2 apps. In deed they offer a powerful way to get data in and out of your app. Thanks for watching Angular 2 forms coffee break course. This has been Reggie Dawson for Tuts+.

Back to the top