InputButtonUnitComponentto use HTML form elements by wrapping everything with
<form>tag and add the
type="submit"attribute to the button. When complete, your template looks something like this:
FormsModuleadd it to the array of imports in the
app.module.ts. Don't forget to import the library at the top of the
[()]syntax is called banana in the box). Take a moment to read more about it in the Angular forms documentation.
ngModelon the To Do title to bind with our pre-existing
titleproperty (the one in
.tsfile) and to the template reference variable for our form (
type="submit"to your button but at the moment it's not used at all. The addition of items works due to old logic on button click and pressing Enter.
ngSubmitwhich is part of
ngFormdirective instead. The syntax is similar to the click handler, but instead of handling the
(click)action by calling a method, we handle the
(ngSubmit)action and call a method.
<form>tag. The form will now know that when user wants to submit the value it needs to run
onSubmit(), but instead of writing a new method, we can use
submitValuemethod after we apply a small refactoring change.
submitValue()instead. For the input parameter, instead of passing the
#todoItemvalue, we can pass the entire form by refering to the template variable for the form, such as
requireddirective to the input so it will not allow to submit empty value.
NgForm. Update the input parameter name and type to match the new data type we're passing in.
submitValue()method. Now that we are passing in the entire form as the input parameter, we can use the built-in properties of
NgFormto check validity. In your
ifstatement, check for
NgFormallows to get values from the form. You've gave the
titleand now you may refer directly to it (
newTitleFormto see the results. 🎉
NgFormmethods to clear inputs after submitting a value.