Resetting the Form3:07 with Andrew Chalkley
In this video we'll reset the form after submitting.
Now, I want to reset the form after I've added a comment. 0:00 To do that I need to access the form itself. 0:04 Remember, I said earlier that angular applies the mg form directive 0:07 automatically, so we didn't need to apply it ourselves. 0:11 Well, if we want to access the form and call reset form on it. 0:15 Then, we definitely need to define NJ form. 0:20 On the form element in the entry comment form component dot 0:24 html we need to create a local variable. 0:28 Local variables are created by using the pound sign and 0:31 then the name of the variable. 0:35 Then we assign our new NG form. 0:40 Back in the entry comment form component TS file, 0:44 we'll need to connect the form to our component class. 0:48 We'll start by importing the view child decorator. 0:52 The ViewChild decorator lets the component inspect the template for local variables. 0:57 And design this local variables as member properties of the component. 1:03 In the body of our entry comment form component class. 1:07 We can add comment form as a member and 1:11 call the ViewChild decorator. 1:17 And bind it to the local variable we just created in the template. 1:21 Now, it's not necessary, but 1:34 I prefer to bring in the type definitions when possible. 1:36 In our case, the commentForm variable that we'll be passing into the submit 1:39 function Will be an instance on ngForm. 1:45 I'm going to import ngForm 1:51 From @angular/forms. 1:59 Then I can update the type definitions. 2:04 Now we can do a bunch of stuff when the form is submitted. 2:13 But for now, we'll just reset the form to a pristine state. 2:17 Now we can call the reset form method. 2:21 On the commentForm at the bottom of the onSubmit method. 2:24 You'll notice, as soon as you press the period key, 2:28 you can see all the properties and methods you can call on the form. 2:31 This will come in handy later. 2:34 Let's try it out. 2:40 Cool, our form pushes the new comment to the list of comments and 2:57 immediately resets the form. 3:01 Next, we'll post the comment to the API. 3:04
You need to sign up for Treehouse in order to download course files.Sign up