You are on page 1of 29

Header

Microsoft Virtual Academy

Mastering Angular, Part 5


Template Forms
Eric W. Greene

Produced by
• What are Template Forms?
• Template Forms compared to Reactive Forms
• Getting Started with Angular
• Demo: Setting Up the Angular Starter Application
• Binding with NgModel
• Demo: Binding an Input Control with NgModel
• Angular and Two-Way Data Binding
• Demo: Exploring NgModel
• Organizing Controls with Forms and Groups
• Demo: Using Forms and Groups
• Binding to Many Kinds of Controls
• Demo: Working with Various Kinds of Inputs, Text Area, and Select
• Form Submission
• Demo: Submitting a Form
• Angular supports two form systems: Template Forms and Reactive Forms
• Reactive Forms are covered in the Angular Reactive Forms course
• Template Forms use the directives: NgForm, NgModelGroup, and
NgModel to connect HTML5 forms to a tree of form control objects and
the component model
• The tree of form control objects contain information about the form
and it's controls such as validation state
• The component model contains the information entered via the form
Template Forms compared to Reactive Forms

• Template forms use a declarative approach to configuring Angular forms


• Reactive forms use an imperative approach to configuring Angular forms
and require a little more work to configure
• Template forms provide a directive, NgModel, to connect the
component model to the form control
• Reactive Forms do not directly connect form controls to the component
model, additional code is needed to extract the form data
• Template forms are not available until the second change detection
cycle
Template Forms compared to Reactive Forms

• Template forms are more familiar to AngularJS developers transitioning


to Angular
• Arguably, Reactive forms are more familiar to jQuery and React
developers
• Template forms are useful, but the trends towards reactive programming
will continue to grow and as a result, template forms will become less
popular than reactive forms
• Nevertheless, the Angular team is committed to Template forms, and
they represent one of two options in an Angular application
• Angular applications require some initial project configuration to get up
and running
• There are many ways to get started
• Angular CLI
• Numerous Starter Projects
• From Scratch
• This course will use a starter project configured with WebPack 2
• The WebPack development server will serve the web pages, and
WebPack will bundle the application files
• The initial starter project can be downloaded from GitHub
• Git is not required, simply fire up a web browser, and visit the following
link
• https://github.com/training4developers/mastering-angular-starter
• In the demonstration we will download, configure and fire up the project
Demo
Setting Up the Angular Starter Application
Binding with NgModel

• The directive NgModel connects a model property to an input control


• Unlike AngularJS, NgModel is not distributed with the core Angular
module
• NgModel is distributed via the @angular/forms package, and must be
registered with the application module to be used
import { FormsModule } from "@angular/forms";
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ],
})
export class AppModule { }
Binding with NgModel

• Once imported, the directive import { Component } from "@angular/core";


can be used in templates @Component({
throughout the application selector: "main",
template: `
• NgModel is applied to a form Value: {{message}}<br>
control such as an input `,
<input type="text" [(ngModel)]="message">

control })
export class AppComponent {
• NgModel assigns the value of
the model to the control, and public message: string = "Hello World!";

it outputs the new value to }


update the model
Binding with NgModel

• The value of the message


property, 'Hello World!' is
display with a template
variable, and populates the
input control
• When the value in the input
control is modified, the
template variable is updated
immediately
Demo
Binding an Input Control with NgModel
• Angular forms have three parts which make up the whole
• Form and Control Elements
• Form and Control Objects
• Component Model
• NgModel connects the Component Model directly to the Elements
• Reactive Forms connect Form and Control Object and Elements to each
other, then developer supplied component code connects the Form and
Control Objects to the Component Model
• The connection created by NgModel is called two-way binding
• What is meant by two-way data binding?
• Essentially, two-way data binding is connecting a property of the
component model to a form control element in a way in which data
flows two-ways, from the model to the control, and from the control to
the model
• On the surface, this approach to data binding seems useful, and for
one specific case it is
• The specific case is where the component model will not be updated
from another source while it is bound to the form control element
• The two-way data binding provided by NgModel is not built into the
core of Angular, its simply a coupling of property and event binding
implemented into a directive
• Unlike AngularJS which required the use of two-way data binding, the
core of Angular has no support for it
• Instead, NgModel uses the feature of inputs (property binding) and
outputs (event binding) supported by Angular components to achieve
two-way binding
• NgModel can be utilized in a one-way binding manner, but such an
approach is better accomplished with Reactive forms
The key difference is
the location of the
component code and
the bi-directional
arrows. Both,
approaches can update
the model, the key is
managing the updates
[ngModel] (ngModelChange) through component
code versus automatic [(ngModel)]
bindings. Two-way
results in more than
one source of truth for
the component model.

One-Way Data Binding Two-Way Data Binding


Demo
Exploring NgModel
Organizing Controls with Forms

• While a single control bound to NgModel can be used to collect user


data, its very common to have many controls displayed on a page
• To help organize many controls, forms and groups are used
• HTML5 provides several elements for organizing controls
• The form element is used by HTML to collect and send the values
entered into the form controls
• The fieldset element is used to group related controls (and their
labels) within a form
• Angular provides directives with behavior analogous to these HTML5
elements
Organizing Controls with Forms

• The directive NgForm is applied to a form element to connect the


NgModels of the child controls to facilitate aggregated form validation,
and collection of form values
• NgForm can be applied to other elements as well, it does not use any of
the built-in form element features
• To apply the NgForm directive, simply apply "ngForm" to an element
• If a form element should not have NgForm applied, add the attribute
"noNgForm" to it
• Finally, all controls within a form with NgModel applied must have the
name attribute set with a name which reasonable for the control
Organizing Controls with Forms

• The directive NgModelGroup provides a group mechanism to capture


validation state at an intermediary level between the controls and the
form itself
• NgModelGroup can be applied to any element such as a div or fieldset
• When applied to an element, the name of the NgModelGroup should
be assigned through an attribute value
• The name of the model group will be used on the Form Object to
organize the controls and to generate the form value object model
Demo
Using Forms and Groups
Binding to Many Kinds of Controls

• HTML5 forms provide several kinds of controls which can be configured


• Input Control – Collects a single value
• Text Area Control – Collects paragraphs of text
• Select Control – Collects a single value or multiple values from a given
list of options
• Content Editable – Changes any element into an editable region
• NgModel works with all controls except for elements marked as
Content Editable
Binding to Many Kinds of Controls

• Input controls support many types of UI elements for collecting data


such as text, numbers, email addresses, range of numbers, colors, dates,
etc…
• Many web browser provide a UI feature of allowing text areas to be
resized by the user making them an excellent way to collect longer
paragraphs of text
• Select controls can appear as drop down controls or list boxes. When
used as a list box, one or more values can be collected
• NgModel takes are of the details of how to connect to each kind of
form control making it easier for the developer to use them
Demo
Working with Various Kinds of Inputs, Text Area, and
Select
Form Submission

• Typically, users of older-style, server-side web applications would submit


their forms by clicking a submit button within a form
• Clicking the submit button would trigger the browser to submit the
form by collecting the data from the various form controls and posting it
up to the server
• With client-side applications, such as Angular applications, submitting to
the server is longer desired
• Instead, the data collected by the form is processed with JavaScript
code, and if something needs to be sent to the server, then AJAX or web
sockets are used
Form Submission

• Angular Forms maintain a status of being submitted or not submitted


• The status cannot be changed directly, instead the form must be
submitted via a button click or reset via a button click
• Angular Forms use the built-in capabilities of the browser for submitting
and resetting forms to trigger the form status
• A second option is to ignore form status all together, and simply wire up
buttons that respond to click events, and then perform the appropriate
action for the button which is clicked
• The default action of the form should always be wired up via ngSubmit
to enable 'enter' key submission with all other button handling clicks
only
Demo
Submitting a Form
• In this course, Angular Template Forms were presented
• Using NgModel, HTML5 form controls can be bound to the component
model
• Multiple controls can be organized into forms using NgForm and
NgModelGroup
• Form Submission was explained and explored
• Various binding patterns were explained
• In other courses, Reactive Forms and Form Validation are covered

You might also like