After the docs UI redesign `h2` tags got a border top. `border-top: 1px solid #dbdbdb;`; In the sections of Getting Started guide in order to separate `What's next` from above content an `<hr />` tag was used, that now becomes unnecessary. This commit removes unnecessary `<hr />` tags. PR Close #40693
3.7 KiB
Using forms for user input
This guide builds on the Managing Data step of the Getting Started tutorial, Get started with a basic Angular app.
This section walks you through adding a form-based checkout feature to collect user information as part of checkout.
Define the checkout form model
This step shows you how to set up the checkout form model in the component class. The form model determines the status of the form.
-
Open
cart.component.ts. -
Import the
FormBuilderservice from the@angular/formspackage. This service provides convenient methods for generating controls.
- Inject the
FormBuilderservice in theCartComponentconstructor(). This service is part of theReactiveFormsModulemodule, which you've already imported.
- To gather the user's name and address, use the
FormBuildergroup()method to set thecheckoutFormproperty to a form model containingnameandaddressfields.
- Define an
onSubmit()method to process the form. This method allows users to submit their name and address. In addition, this method uses theclearCart()method of theCartServiceto reset the form and clear the cart.
The entire cart component class is as follows:
Create the checkout form
Use the following steps to add a checkout form at the bottom of the Cart view.
-
At the bottom of
cart.component.html, add an HTML<form>element and a Purchase button. -
Use a
formGroupproperty binding to bindcheckoutFormto the HTML<form>.
- On the
formtag, use anngSubmitevent binding to listen for the form submission and call theonSubmit()method with thecheckoutFormvalue.
- Add
<input>fields fornameandaddress, each with aformControlNameattribute that binds to thecheckoutFormform controls fornameandaddressto their<input>fields. The complete component is as follows:
After putting a few items in the cart, users can review their items, enter their name and address, and submit their purchase.
To confirm submission, open the console to see an object containing the name and address you submitted.
What's next
You have a complete online store application with a product catalog, a shopping cart, and a checkout function.
Continue to the "Deployment" section to move to local development, or deploy your app to Firebase or your own server.
