{ "id": "start/start-forms", "title": "Using forms for user input", "contents": "\n\n\n
This guide builds on the Managing Data step of the Getting Started tutorial, Get started with a basic Angular app.
\nThis section walks you through adding a form-based checkout feature to collect user information as part of checkout.
\nThis step shows you how to set up the checkout form model in the component class.\nThe form model determines the status of the form.
\nOpen cart.component.ts
.
Import the FormBuilder
service from the @angular/forms
package.\nThis service provides convenient methods for generating controls.
Inject the FormBuilder
service in the CartComponent
constructor()
.\nThis service is part of the ReactiveFormsModule
module, which you've already imported.
To gather the user's name and address, use the FormBuilder
group()
method to set the checkoutForm
property to a form model containing name
and address
fields.
Define an onSubmit()
method to process the form.\nThis method allows users to submit their name and address.\nIn addition, this method uses the clearCart()
method of the CartService
to reset the form and clear the cart.
The entire cart component class is as follows:
\nUse the following steps to add a checkout form at the bottom of the Cart view.
\nAt the bottom of cart.component.html
, add an HTML <form>
element and a Purchase button.
Use a formGroup
property binding to bind checkoutForm
to the HTML <form>
.
On the form
tag, use an ngSubmit
event binding to listen for the form submission and call the onSubmit()
method with the checkoutForm
value.
Add <input>
fields for name
and address
, each with a formControlName
attribute that binds to the checkoutForm
form controls for name
and address
to their <input>
fields.\nThe 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.
\nTo confirm submission, open the console to see an object containing the name and address you submitted.
\nYou have a complete online store application with a product catalog, a shopping cart, and a checkout function.
\nContinue to the \"Deployment\" section to move to local development, or deploy your app to Firebase or your own server.
\n\n \n