AngularJS form
The AngularJS framework provides support for HTML forms and form inputs.
An Angular form coordinates a set of data-bound user controls, tracks changes, validates input, and presents errors.
Contents
Summary
- Build an Angular form with a component and template
- Two-way data bind with [(ngModel)] syntax for reading and writing values to input controls
- Track the change state and validity of form controls using ngModel in combination with a form
- Provide strong visual feedback using special CSS classes that track the state of the controls
- Display validation errors to users and enable/disable form controls
- Use template reference variables for sharing information among HTML elements
Template-driven forms
You can create forms by writing templates in the Angular template syntax with the form-specific directives and techniques.
Working with forms
If you simply want to get the value of a form input, use ngModel.
If you want to get the state of form input, use a form control.
Inputs can be grouped together using group controls.
Form control
A form control is an HTML form input element, such as input (HTML element). AngularJS provides input binding for programmatic handling of form controls, such as input validation.
Form group control
A form group control allows the grouping together of two or more form controls.
FormBuilder
FormBuilder is an Angular2 feature for working with forms.
Example
import { Component } from 'angular2/common'; import { FORM_DIRECTIVES } from 'angular2/common'; import { MATERIAL_DIRECTIVES } from 'ng2-material/all'; @Component ({ selector: 'some-form', template: ` <div> <form #userForm="ngForm" #nameGroup="ngForm"> <div ngControlGroup="name" #nameGroup="ngForm"> <md-input-container [class.err]="!firstName.valid"> <label>First Name</label> <input required md-input [(ngModel)]="user.firstName" #firstName="ngForm" placeholder="Enter first name" class="mdl-textfield__input" type="text"> </md-input-container> ... etc.... </div> <div class="mdl-card__actions"> <button type="submit" (click)="cancelled.emit(selectedItem)" class="mdl-button mdl-js-button mdl-js-ripple-effect">Cancel</button> <button type="submit" (click)="cancelled.emit(selectedItem)" class="mdl-button mdl-js-button mdl-button--colored mdl-js-ripple-effect"> </div> </form> `, directives: [ FORM_DIRECTIVES ], styles: [`...`] }) export class FormComponent { constructor(private _builder: FormBuilder) { this.userForm = _builder.group ({ nameGroup: _builder.group ({ firstName: [this.user.firstName, Validators.required], lastName: [this.user.lastName, Validators.required] }) }) } }