9 Forms

 

This chapter covers

  • Creating forms using Angular’s forms libraries
  • Deciding between using Reactive or Template forms
  • Validating forms with custom logic
  • Accessing data and watching input changes
  • Submitting form data and handling errors gracefully
  • Creating custom form controls

Just about every application uses forms in some way, if only to do something simple like log in or manage settings. HTML comes with a number of form elements by default, such as inputs, selects, and buttons, and Angular provides a way to use these native elements and add some power to them. We’ve used forms in several previous examples, but in this chapter we’ll dig into them much more completely.

Angular provides two approaches to building forms: reactive forms and template forms. I’ll discuss the differences at length shortly, though they’re largely in whether you define the form in your controller or in the template. You’re not limited to choosing only one or the other form, but typically applications will try to remain consistent with one of them.

With template forms, we’ll see how to describe your forms primarily using the NgModel directive, which is used to define the form structure. With reactive forms, you declare the form structure yourself in the controller, and the template renders it out.

9.1 Setting up the chapter example

9.1.1 Review the app before starting

9.2 Template-driven forms

9.2.1 Binding model data to inputs with NgModel

9.2.2 Validating form controls with NgModel

9.2.3 Custom validation with directives

9.2.4 Handling submit or cancel events

9.3 Reactive forms

9.3.1 Defining your form

9.3.2 Implementing the template

9.3.3 Watching changes

9.3.4 Custom validators with reactive forms

9.3.5 Handling submit or cancel events

9.3.6 Which form approach is better?

9.4 Custom form controls

Summary

sitemap