Angular 2 makes creating forms a breeze with its new ngForm, ngModel, and ngModelGroup features. This course walks you through how to set up your forms, validation, and styling.
ngModel is a very powerful feature of Angular 2, but it isn’t enabled by default. You need to import the Angular 2
FormsModule and use the proper syntax around the
ngModel directive to enable the features (such as automatically updating from an ngModel) that you would expect.
Checking the validity of an Angular 2 input using ngModel is simply a matter of getting a reference to the ngModel itself. You get the reference by using the
#ref syntax, assigning it a name, then
ngModel will check all of the validity rules for you.
Forms in Angular 2 are essentially wrappers around
inputs that group the input values together into an object and also check that all the inputs are valid. Angular 2 ‘s
ngForm allows you to get a reference to that object and validity and use them to display information about the form or use the
ngSubmit event to save information from the form.
ngModelGroup directive allows you to group together related inputs so that you structure the object represented by the form in a useful and predictable way.
ngModelGroup is often used in combination with
fieldset as they mostly represent the same idea of “grouping together inputs.”
Inputs using Angular 2’s
ngModel automatically apply style classes of
.ng-invalid each time the input’s validity changes. These classes allow you easily add your own styles simply by declaring the
styles in your
ngModel exposes more than just validity, it even gives you the states of whether the
input has been “touched” or changed. This lesson explains and compares those states so you can use them to make complex validity requirements.
Angular 2 forms provide RxJS streams for you to work with the data and validity as it flows out of the forms. These streams allow you handle complex scenarios and asynchronous scenarios with relative ease. This example shows you how to log out the values of the form when the form is valid.
Using Radio Buttons in Angular 2 requires a basic understanding of forms as well as how their
labels will match up with each input. This lesson shows how to use
*ngFor with radio buttons and covers the quirks of the
id property and
for attributes as well as how to style validation of radio buttons.
John Lindquist is a co-founder of egghead.io
John has spent the majority of his career developing Rich Web Applications. Before starting egghead.io, John worked at JetBrains as a WebStorm evangelist, and before that he was a Technical Architect at Isobar leading large teams in building the latest and greatest in web apps for the Air Force, HBO, and Bloomberg.