Angular 2
Forms

Forms Overview
- Forms support has been extended in Angular 2
- There are two approaches:
-
Template-Driven
- Form validations and inputs are handled in the template
-
Model-Driven
- Form validation and inputs are handled by code using Angular 2 Form model
-
Template-Driven
Template-Driven
- Template-Driven Forms use a combination of builtin Directives and local template variables to handle the form:
- NgForm - Allows getting form information and override default submit behavior
- NgControl - Directive for tracking state and naming of each form elements in ngForm.
- NgSumbit - Exectues an event handler on button type="submit"
- By default the <form> element is selected by NgForm Directive even if not explicitly specified. This can be reverted using the NgNoFrom Directive on <form> element.
Template-Driven
-
Local template variables are used on the form and each input to get information
- Local variables in this context get the content of the Directives ngForm, ngControl and not the element.
This is why the syntext is
#<variable>="ngForm" (ngForm is exported from these directives)
- Local variables in this context get the content of the Directives ngForm, ngControl and not the element.
- Local variables can be used to check validations either at input level or Form level
- Local variables can be used to send specific or all Form data in the ngSubmit event handler
Template-Driven
- Builtin validation are supported:
- required - Requires a form control to have a non-empty value
- minlength - Requires a form control to have a value of a minimum length
- maxlength - Requires a form control to have a value of a maximum length
- pattern - Requires a form control’s value to match a given regex
- Custom validation can be added using Directive that uses validator API
Template-Driven
- Example
<form #f="ngForm" (ngSubmit)="onFormSubmit(f.value)">
<label>Name:</label><input type="text" ngControl="name" #name="ngForm" required /><br />
<div [hidden]="name.valid" [style.color]="'red'">Invalid name input</div>
<label>Email:</label><input type="text" ngControl="email" #email="ngForm" /><br />
<div [hidden]="email.valid " [style.color]="'red'">Invalid email input</div>
<button type="submit" [disabled]="!f.valid">Submit</button>
</form>Forms
By Shaul Ben-Yossef
Forms
- 1,121