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