docs: incorporated forms overview review feedback (#25663)
PR Close #25663
This commit is contained in:
parent
79a2567aa3
commit
8d098d389a
|
@ -3,8 +3,8 @@
|
||||||
|
|
||||||
<h2>Reactive</h2>
|
<h2>Reactive</h2>
|
||||||
|
|
||||||
<app-reactive-name></app-reactive-name>
|
<app-reactive-favorite-color></app-reactive-favorite-color>
|
||||||
|
|
||||||
<h2>Template-Driven</h2>
|
<h2>Template-Driven</h2>
|
||||||
|
|
||||||
<app-template-name></app-template-name>
|
<app-template-favorite-color></app-template-favorite-color>
|
|
@ -0,0 +1,50 @@
|
||||||
|
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
|
||||||
|
import { ReactiveFormsModule } from '@angular/forms';
|
||||||
|
|
||||||
|
import { FavoriteColorComponent } from './favorite-color.component';
|
||||||
|
import { createNewEvent } from '../../shared/utils';
|
||||||
|
|
||||||
|
describe('Favorite Color Component', () => {
|
||||||
|
let component: FavoriteColorComponent;
|
||||||
|
let fixture: ComponentFixture<FavoriteColorComponent>;
|
||||||
|
|
||||||
|
beforeEach(async(() => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [ ReactiveFormsModule ],
|
||||||
|
declarations: [ FavoriteColorComponent ]
|
||||||
|
})
|
||||||
|
.compileComponents();
|
||||||
|
}));
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = TestBed.createComponent(FavoriteColorComponent);
|
||||||
|
component = fixture.componentInstance;
|
||||||
|
fixture.detectChanges();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create', () => {
|
||||||
|
expect(component).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
// #docregion view-to-model
|
||||||
|
it('should update the value of the input field', () => {
|
||||||
|
const input = fixture.nativeElement.querySelector('input');
|
||||||
|
const event = createNewEvent('input');
|
||||||
|
|
||||||
|
input.value = 'Red';
|
||||||
|
input.dispatchEvent(event);
|
||||||
|
|
||||||
|
expect(fixture.componentInstance.favoriteColor.value).toEqual('Red');
|
||||||
|
});
|
||||||
|
// #enddocregion view-to-model
|
||||||
|
|
||||||
|
// #docregion model-to-view
|
||||||
|
it('should update the value in the control', () => {
|
||||||
|
component.favoriteColor.setValue('Blue');
|
||||||
|
|
||||||
|
const input = fixture.nativeElement.querySelector('input');
|
||||||
|
|
||||||
|
expect(input.value).toBe('Blue');
|
||||||
|
});
|
||||||
|
// #enddocregion model-to-view
|
||||||
|
});
|
|
@ -0,0 +1,19 @@
|
||||||
|
import { Component, OnInit } from '@angular/core';
|
||||||
|
import { FormControl } from '@angular/forms';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-reactive-favorite-color',
|
||||||
|
template: `
|
||||||
|
Favorite Color: <input type="text" [formControl]="favoriteColor">
|
||||||
|
`,
|
||||||
|
styles: []
|
||||||
|
})
|
||||||
|
export class FavoriteColorComponent implements OnInit {
|
||||||
|
favoriteColor = new FormControl('');
|
||||||
|
|
||||||
|
constructor() { }
|
||||||
|
|
||||||
|
ngOnInit() {
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,62 +0,0 @@
|
||||||
// #docregion
|
|
||||||
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
|
|
||||||
import { ReactiveFormsModule } from '@angular/forms';
|
|
||||||
|
|
||||||
import { ReactiveNameComponent } from './name.component';
|
|
||||||
import { createNewEvent } from '../../shared/utils';
|
|
||||||
|
|
||||||
// #docregion tests
|
|
||||||
describe('Reactive Name Component', () => {
|
|
||||||
// #enddocregion tests
|
|
||||||
let component: ReactiveNameComponent;
|
|
||||||
let fixture: ComponentFixture<ReactiveNameComponent>;
|
|
||||||
|
|
||||||
beforeEach(async(() => {
|
|
||||||
TestBed.configureTestingModule({
|
|
||||||
imports: [ReactiveFormsModule],
|
|
||||||
declarations: [ReactiveNameComponent]
|
|
||||||
})
|
|
||||||
.compileComponents();
|
|
||||||
}));
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
fixture = TestBed.createComponent(ReactiveNameComponent);
|
|
||||||
component = fixture.componentInstance;
|
|
||||||
fixture.detectChanges();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should create', () => {
|
|
||||||
expect(component).toBeTruthy();
|
|
||||||
});
|
|
||||||
|
|
||||||
// #docregion tests
|
|
||||||
it('should update the value in the control', () => {
|
|
||||||
// update the control value
|
|
||||||
component.name.setValue('Nancy');
|
|
||||||
|
|
||||||
// query the element
|
|
||||||
const input = fixture.nativeElement.querySelector('input');
|
|
||||||
|
|
||||||
// check its value
|
|
||||||
expect(input.value).toBe('Nancy');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should update the value of the input field', () => {
|
|
||||||
// update the control value
|
|
||||||
component.name.setValue('Nancy');
|
|
||||||
|
|
||||||
// query the element
|
|
||||||
const input = fixture.nativeElement.querySelector('input');
|
|
||||||
expect(input.value).toEqual('Nancy');
|
|
||||||
|
|
||||||
// update the form field value
|
|
||||||
input.value = 'Smith';
|
|
||||||
|
|
||||||
// Use utility function to create custom event, then dispatch on the input
|
|
||||||
const event = createNewEvent('input');
|
|
||||||
input.dispatchEvent(event);
|
|
||||||
|
|
||||||
expect(fixture.componentInstance.name.value).toEqual('Smith');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
// #enddocregion
|
|
|
@ -1,17 +0,0 @@
|
||||||
// #docplaster
|
|
||||||
// #docregion
|
|
||||||
import { Component } from '@angular/core';
|
|
||||||
import { FormControl } from '@angular/forms';
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
// #enddocregion
|
|
||||||
selector: 'app-reactive-name',
|
|
||||||
// #docregion
|
|
||||||
template: `
|
|
||||||
Name: <input type="text" [formControl]="name">
|
|
||||||
`
|
|
||||||
})
|
|
||||||
export class ReactiveNameComponent {
|
|
||||||
name = new FormControl('');
|
|
||||||
}
|
|
||||||
// #enddocregion
|
|
|
@ -1,14 +1,14 @@
|
||||||
import { NgModule } from '@angular/core';
|
import { NgModule } from '@angular/core';
|
||||||
import { CommonModule } from '@angular/common';
|
import { CommonModule } from '@angular/common';
|
||||||
import { ReactiveNameComponent } from './name/name.component';
|
|
||||||
import { ReactiveFormsModule } from '@angular/forms';
|
import { ReactiveFormsModule } from '@angular/forms';
|
||||||
|
import { FavoriteColorComponent } from './favorite-color/favorite-color.component';
|
||||||
|
|
||||||
@NgModule({
|
@NgModule({
|
||||||
imports: [
|
imports: [
|
||||||
CommonModule,
|
CommonModule,
|
||||||
ReactiveFormsModule
|
ReactiveFormsModule
|
||||||
],
|
],
|
||||||
declarations: [ReactiveNameComponent],
|
declarations: [FavoriteColorComponent],
|
||||||
exports: [ReactiveNameComponent],
|
exports: [FavoriteColorComponent],
|
||||||
})
|
})
|
||||||
export class ReactiveModule { }
|
export class ReactiveModule { }
|
||||||
|
|
|
@ -0,0 +1,56 @@
|
||||||
|
import { async, ComponentFixture, TestBed, tick, fakeAsync } from '@angular/core/testing';
|
||||||
|
import { FormsModule } from '@angular/forms';
|
||||||
|
|
||||||
|
import { FavoriteColorComponent } from './favorite-color.component';
|
||||||
|
import { createNewEvent } from '../../shared/utils';
|
||||||
|
|
||||||
|
describe('FavoriteColorComponent', () => {
|
||||||
|
let component: FavoriteColorComponent;
|
||||||
|
let fixture: ComponentFixture<FavoriteColorComponent>;
|
||||||
|
|
||||||
|
beforeEach(async(() => {
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
imports: [ FormsModule ],
|
||||||
|
declarations: [ FavoriteColorComponent ]
|
||||||
|
})
|
||||||
|
.compileComponents();
|
||||||
|
}));
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
fixture = TestBed.createComponent(FavoriteColorComponent);
|
||||||
|
component = fixture.componentInstance;
|
||||||
|
fixture.detectChanges();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create', () => {
|
||||||
|
expect(component).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
// #docregion model-to-view
|
||||||
|
it('should update the favorite color on the input field', fakeAsync(() => {
|
||||||
|
component.favoriteColor = 'Blue';
|
||||||
|
|
||||||
|
fixture.detectChanges();
|
||||||
|
|
||||||
|
tick();
|
||||||
|
|
||||||
|
const input = fixture.nativeElement.querySelector('input');
|
||||||
|
|
||||||
|
expect(input.value).toBe('Blue');
|
||||||
|
}));
|
||||||
|
// #enddocregion model-to-view
|
||||||
|
|
||||||
|
// #docregion view-to-model
|
||||||
|
it('should update the favorite color in the component', fakeAsync(() => {
|
||||||
|
const input = fixture.nativeElement.querySelector('input');
|
||||||
|
const event = createNewEvent('input');
|
||||||
|
|
||||||
|
input.value = 'Red';
|
||||||
|
input.dispatchEvent(event);
|
||||||
|
|
||||||
|
tick();
|
||||||
|
|
||||||
|
expect(component.favoriteColor).toEqual('Red');
|
||||||
|
}));
|
||||||
|
// #enddocregion view-to-model
|
||||||
|
});
|
|
@ -0,0 +1,18 @@
|
||||||
|
import { Component, OnInit } from '@angular/core';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-template-favorite-color',
|
||||||
|
template: `
|
||||||
|
Favorite Color: <input type="text" [(ngModel)]="favoriteColor">
|
||||||
|
`,
|
||||||
|
styles: []
|
||||||
|
})
|
||||||
|
export class FavoriteColorComponent implements OnInit {
|
||||||
|
favoriteColor = '';
|
||||||
|
|
||||||
|
constructor() { }
|
||||||
|
|
||||||
|
ngOnInit() {
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,76 +0,0 @@
|
||||||
// #docregion
|
|
||||||
import { async, ComponentFixture, TestBed, tick, fakeAsync } from '@angular/core/testing';
|
|
||||||
import { FormsModule } from '@angular/forms';
|
|
||||||
|
|
||||||
import { createNewEvent } from '../../shared/utils';
|
|
||||||
import { TemplateNameComponent } from './name.component';
|
|
||||||
|
|
||||||
// #docregion tests
|
|
||||||
describe('Template Name Component', () => {
|
|
||||||
// #enddocregion tests
|
|
||||||
let component: TemplateNameComponent;
|
|
||||||
let fixture: ComponentFixture<TemplateNameComponent>;
|
|
||||||
|
|
||||||
beforeEach(async(() => {
|
|
||||||
TestBed.configureTestingModule({
|
|
||||||
imports: [FormsModule],
|
|
||||||
declarations: [TemplateNameComponent]
|
|
||||||
})
|
|
||||||
.compileComponents();
|
|
||||||
}));
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
fixture = TestBed.createComponent(TemplateNameComponent);
|
|
||||||
component = fixture.componentInstance;
|
|
||||||
fixture.detectChanges();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should create', () => {
|
|
||||||
expect(component).toBeTruthy();
|
|
||||||
});
|
|
||||||
|
|
||||||
// #docregion tests
|
|
||||||
it('should update the value in the control', fakeAsync(() => {
|
|
||||||
// update the component instance variable
|
|
||||||
component.name = 'Nancy';
|
|
||||||
|
|
||||||
// run change detection
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
// advance after change detection cycle
|
|
||||||
tick();
|
|
||||||
|
|
||||||
// query the element
|
|
||||||
const input = fixture.nativeElement.querySelector('input');
|
|
||||||
|
|
||||||
expect(input.value).toBe('Nancy');
|
|
||||||
}));
|
|
||||||
|
|
||||||
it('should update the value of the input field', fakeAsync(() => {
|
|
||||||
// update component instance variable
|
|
||||||
component.name = 'Nancy';
|
|
||||||
|
|
||||||
// run change detection
|
|
||||||
fixture.detectChanges();
|
|
||||||
|
|
||||||
// advance after change detection cycle
|
|
||||||
tick();
|
|
||||||
|
|
||||||
// query the element
|
|
||||||
const input = fixture.nativeElement.querySelector('input');
|
|
||||||
expect(input.value).toEqual('Nancy');
|
|
||||||
|
|
||||||
// update the form field value
|
|
||||||
input.value = 'Smith';
|
|
||||||
|
|
||||||
// Use utility function to create custom event, then dispatch on the input
|
|
||||||
const event = createNewEvent('input');
|
|
||||||
input.dispatchEvent(event);
|
|
||||||
|
|
||||||
// advance after change detection cycle
|
|
||||||
tick();
|
|
||||||
|
|
||||||
expect(component.name).toEqual('Smith');
|
|
||||||
}));
|
|
||||||
});
|
|
||||||
// #enddocregion
|
|
|
@ -1,16 +0,0 @@
|
||||||
// #docplaster
|
|
||||||
// #docregion
|
|
||||||
import { Component } from '@angular/core';
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
// #enddocregion
|
|
||||||
selector: 'app-template-name',
|
|
||||||
// #docregion
|
|
||||||
template: `
|
|
||||||
Name: <input type="text" [(ngModel)]="name">
|
|
||||||
`
|
|
||||||
})
|
|
||||||
export class TemplateNameComponent {
|
|
||||||
name = '';
|
|
||||||
}
|
|
||||||
// #enddocregion
|
|
|
@ -1,14 +1,14 @@
|
||||||
import { NgModule } from '@angular/core';
|
import { NgModule } from '@angular/core';
|
||||||
import { CommonModule } from '@angular/common';
|
import { CommonModule } from '@angular/common';
|
||||||
import { TemplateNameComponent } from './name/name.component';
|
|
||||||
import { FormsModule } from '@angular/forms';
|
import { FormsModule } from '@angular/forms';
|
||||||
|
import { FavoriteColorComponent } from './favorite-color/favorite-color.component';
|
||||||
|
|
||||||
@NgModule({
|
@NgModule({
|
||||||
imports: [
|
imports: [
|
||||||
CommonModule,
|
CommonModule,
|
||||||
FormsModule
|
FormsModule
|
||||||
],
|
],
|
||||||
declarations: [TemplateNameComponent],
|
declarations: [FavoriteColorComponent],
|
||||||
exports: [TemplateNameComponent]
|
exports: [FavoriteColorComponent]
|
||||||
})
|
})
|
||||||
export class TemplateModule { }
|
export class TemplateModule { }
|
||||||
|
|
|
@ -2,258 +2,193 @@
|
||||||
|
|
||||||
Handling user input with forms is the cornerstone of many common applications. Applications use forms to log in, to update a profile, to enter sensitive information, and to perform many other data-entry tasks.
|
Handling user input with forms is the cornerstone of many common applications. Applications use forms to log in, to update a profile, to enter sensitive information, and to perform many other data-entry tasks.
|
||||||
|
|
||||||
Angular provides two different approaches to handling user input through forms: reactive and template-driven. Each set of forms promote a distinct way of processing forms and offers different advantages. The sections below provide a comparison of the two approaches and when each one is applicable. There are many different factors that influence your decision on which approach works best for your situation. Whether you’re using reactive or template-driven forms, these concepts are key to understanding the mechanisms underneath each solution.
|
Angular provides two different approaches to handling user input through forms: reactive and template-driven. Each set of forms promote a distinct way of processing forms and offers different advantages. There are many different factors that influence your decision on which approach works best for your situation. Whether you’re using reactive or template-driven forms, these concepts are key to understanding the mechanisms underneath each solution. The sections below provide a comparison of the key differences, common building blocks, data flows, validation and testing, and mutability and scalability when deciding between reactive and template-driven forms.
|
||||||
|
|
||||||
|
**In general:**
|
||||||
|
|
||||||
|
* **Reactive forms** are more robust: they are more scalable, reusable, and testable. If forms are a key part of your application, or you're already using reactive patterns for building your application, use reactive forms.
|
||||||
|
* **Template-driven forms** are useful for adding a simple form to an app, such as an email list signup form. They are easy to add to an app, but they do not scale as well as reactive forms. If you have very basic form requirements and logic that can be managed solely in the template, use template-driven forms.
|
||||||
|
|
||||||
## Key differences
|
## Key differences
|
||||||
|
|
||||||
The table below summarizes the key differences in reactive and template driven forms.
|
The table below summarizes the key differences in reactive and template driven forms.
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
td, th {vertical-align: top}
|
table {width: 100%};
|
||||||
|
td, th {vertical-align: top};
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<table width="100%">
|
||Reactive|Template-driven|
|
||||||
|
|--- |--- |--- |
|
||||||
<tr>
|
|Setup/Form Model|More explicit/Created in the component class.|Less explicit/Created by the directives.|
|
||||||
|
|Data model|Structured|Unstructured|
|
||||||
<th>
|
|Predictability|Synchronous|Asynchronous|
|
||||||
|
|Form validation|Functions|Directives|
|
||||||
</th>
|
|Mutability|Immutable|Mutable|
|
||||||
|
|Scalability|Low-level API access|Abstraction on top of APIs|
|
||||||
<th>
|
|
||||||
Reactive
|
|
||||||
</th>
|
|
||||||
|
|
||||||
<th width="40%">
|
|
||||||
Template-Driven
|
|
||||||
</th>
|
|
||||||
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<tr>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Setup
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
More Explicit
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Less Explicit
|
|
||||||
</td>
|
|
||||||
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<tr>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Source of truth
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
The form model
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
The directives in the template
|
|
||||||
</td>
|
|
||||||
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<tr>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Form Model creation
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Class
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Form Directives
|
|
||||||
</td>
|
|
||||||
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<tr>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Predictability
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Synchronous
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Asynchronous
|
|
||||||
</td>
|
|
||||||
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<tr>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Consistency
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Immutable
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Mutable
|
|
||||||
</td>
|
|
||||||
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<tr>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Data model
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Structured
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Unstructured
|
|
||||||
</td>
|
|
||||||
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<tr>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Custom Validators
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Functions
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Directives
|
|
||||||
</td>
|
|
||||||
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<tr>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Scalability
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Low-level API access
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
Abstraction on top of APIs
|
|
||||||
</td>
|
|
||||||
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
</table>
|
|
||||||
|
|
||||||
In general:
|
|
||||||
|
|
||||||
* **Reactive forms** are more robust: they are more scalable, reusable, and testable. If forms are a key part of your application, or you're already using reactive patterns for building your application, use reactive forms.
|
|
||||||
* **Template-driven forms** are useful for adding a simple form to an app, such as a single email list signup form. They are easy to add to an app, but they do not scale as well as reactive forms. If you have very basic form requirements and logic that can be managed solely in the template, use template-driven forms.
|
|
||||||
|
|
||||||
## A common foundation
|
## A common foundation
|
||||||
|
|
||||||
Both reactive and template-driven forms share underlying building blocks, the `FormControl`, `FormGroup` and `FormArray`. A `FormControl` instance tracks the value and validation status of an individual form control element, a `FormGroup` instance tracks the same values and statuses for a collection, and a `FormArray` instance tracks the same values and statues for an array of form controls. How these control instances are created and managed with reactive and template-driven forms will be discussed later in this guide.
|
Both reactive and template-driven forms share underlying building blocks.
|
||||||
|
|
||||||
## Control value accessors
|
- A `FormControl` instance that tracks the value and validation status of an individual form control.
|
||||||
|
- A `FormGroup` instance that tracks the same values and statuses for a collection of form controls.
|
||||||
|
- A `FormArray` instance that tracks the same values and statues for an array of form controls.
|
||||||
|
- A `ControlValueAccessor` that creates a bridge between Angular form controls and native DOM elements.
|
||||||
|
|
||||||
Control value accessors define a bridge between Angular forms and native DOM elements. The `ControlValueAccessor` interface defines methods for interacting with native elements including: reading from and writing values to them, disabling or enabling their elements, and providing callback functions for when the control's value changes in the UI or becomes touched. A built-in accessor is attached to every form field when using either forms module in Angular, unless a custom value accessor has been activated on that field.
|
How these control instances are created and managed with reactive and template-driven forms is introduced in the [form model](#the-form-model) section below and detailed further in the [data flow section](#data-flow-in-forms) of this guide.
|
||||||
|
|
||||||
|
## The form model
|
||||||
|
|
||||||
|
In reactive forms, the source of truth is the form model (the `FormControl` instance)
|
||||||
|
|
||||||
|
**Diagram 1 - reactive forms**
|
||||||
|
|
||||||
|
With reactive forms, the form model is explicitly defined in the component class. The reactive form directive (in this case, `FormControlDirective`) then links the existing form control instance to a specific form element in the view using a value accessor. Updates from the view-to-model and model-to-view are synchronous and not dependent on the UI rendered.
|
||||||
|
|
||||||
|
In template-driven forms, the source of truth is the template.
|
||||||
|
|
||||||
|
**Diagram 2 - template-driven forms**
|
||||||
|
|
||||||
|
The abstraction of the form model promotes simplicity over structure. It is less explicit, but you no longer have direct control over the form model. Updates from the view-to-model and model-to-view must pass through directives (in this case, the `NgModel` directive), and be asynchronous to work around the change detection cycle. Value changes are delayed until the next tick, which allows change detection to complete and a new change detection process to be triggered with the updated value.
|
||||||
|
|
||||||
## Data flow in forms
|
## Data flow in forms
|
||||||
|
|
||||||
When building forms in Angular, it's important to understand how the the framework handles data flowing from the user or from programmatic changes. Reactive and template-driven follow two different strategies when handling these scenarios. Using a simple component with a single input field, we can illustrate how changes are handled.
|
When building forms in Angular, it's important to understand how the the framework handles data flowing from the user or from programmatic changes. Reactive and template-driven forms follow two different strategies when handling form input. The components below use an input field to manage the *favorite color* value and to show how changes are handled.
|
||||||
|
|
||||||
### Data flow in reactive forms
|
### Data flow in reactive forms
|
||||||
|
|
||||||
Here is a component with an input field for a single control using reactive forms.
|
Here is a component with an input field for a single control implemented using reactive forms.
|
||||||
|
|
||||||
<code-example path="forms-overview/src/app/reactive/name/name.component.ts">
|
<code-example path="forms-overview/src/app/reactive/favorite-color/favorite-color.component.ts">
|
||||||
</code-example>
|
</code-example>
|
||||||
|
|
||||||
Let’s look at how the data flows for an input with reactive forms.
|
The diagrams below shows how the data flows for an input with reactive forms.
|
||||||
|
|
||||||
**Diagram of Input Event Flow For Reactive Forms**
|
**Diagram 3 - View-To-Model Flow For Reactive Forms**
|
||||||
|
|
||||||
In reactive forms, the source of truth is the form model (in this case, the `FormControl` instance), which is explicitly defined in the component class. This model is created independently of the UI and can be used to provide an initial value for the control. The reactive form directive (in this case, `FormControlDirective`) then links the existing form control instance to a specific form element in the view using a value accessor.
|
From the view-to-model:
|
||||||
|
|
||||||
When text is entered into the input field, the field's value accessor immediately relays the new value to the FormControl instance, which then emits the value through the valueChanges observable.
|
1. The form input element emits an input event with the latest value.
|
||||||
|
1. The control value accessor on the form input element immediately relays the new value to the `FormControl` instance, which then emits the value through the valueChanges observable.
|
||||||
|
|
||||||
With reactive forms, you have full control over the form model without ever rendering the UI. The source of truth is always up-to-date, because it is synchronously updated at the time changes are made.
|
**Diagram 4 - Model-To-View Flow For Reactive Forms**
|
||||||
|
|
||||||
|
From the model-to-view:
|
||||||
|
|
||||||
|
1. The form control instance sets the latest value and emits the latest value through the `valueChanges` observable.
|
||||||
|
1. The control value accessor on the form input element is updates the element with the latest value.
|
||||||
|
|
||||||
### Data flow in template-driven forms
|
### Data flow in template-driven forms
|
||||||
|
|
||||||
Here is a component with an input field for a single control using template-driven forms.
|
Here is the same component with an input field for a single control implemented using template-driven forms.
|
||||||
|
|
||||||
<code-example path="forms-overview/src/app/template/name/name.component.ts">
|
<code-example path="forms-overview/src/app/template/favorite-color/favorite-color.component.ts">
|
||||||
</code-example>
|
</code-example>
|
||||||
|
|
||||||
Let’s compare the same data flows with template-driven forms.
|
The diagrams below shows how the data flows for an input with template-driven forms.
|
||||||
|
|
||||||
**Diagram of Input Event Flow For Template-driven Forms**
|
**Diagram of Input Event Flow For Template-driven forms**
|
||||||
|
|
||||||
In template-driven forms, the source of truth is the template, so developers create their desired form through the placement of template-driven directives such as `NgModel` and `NgModelGroup`. The directives then create the `FormControl` or `FormGroup` instances that make up the form model, link them with form elements through a value accessor, and manage them within the constraints of the template's change detection cycle.
|
**Diagram 5 - View-To-Model Flow For Template-driven forms**
|
||||||
|
|
||||||
This abstraction promotes simplicity over structure. It is less explicit, but you no longer have direct control over the form model. It is simple to add directives, but because these directives are dependent on the UI, they must work around the change detection cycle. Programmatic value changes are registered during change detection (as they occur through an `Input` to a directive), so it's not possible to update the value and validity immediately because it may affect elements that have already been checked in that view, for example, the parent form. For this reason, value changes are delayed until the next tick, which allows change detection to complete and a new change detection process to be triggered with the updated value. In other words, the process happens asynchronously and introduces unpredictability for querying the source of truth.
|
From the view-to-model:
|
||||||
|
|
||||||
## Custom validation
|
1. The form input element emits an input event with the latest value.
|
||||||
|
1. The control value accessor uses the `NgModel` directive to update its model, queues an async task to set the value for the internal form control instance.
|
||||||
|
1. After the change detection cycle completes, the task to set the form control instance value is called, when then emits the latest value through the `valueChanges` observable.
|
||||||
|
1. The `ngModelChange` event fires on the `NgModel` directive, which then updates the `favoriteColor` value in the component.
|
||||||
|
|
||||||
Validation is an integral part of managing any set of forms. Whether you’re checking for required fields or querying an external API for an existing username, Angular provides a set of built-in validators as well as the ability to create custom validators. With reactive forms, custom validators are functions that receive a control to validate. Because template-driven forms are tied to directives, custom validator directives must be created to wrap a validator function in order to use it in a template.
|
**Diagram 6 - Model-To-View Flow For Reactive Forms**
|
||||||
|
|
||||||
For more on form validation, visit the [Form Validation](guide/form-validation) guide.
|
From the model-to-view:
|
||||||
|
|
||||||
|
1. The `favoriteColor` value is updated in the component.
|
||||||
|
1. Change detection calls the `ngOnChanges` method on the `NgModel` directive instance, updates the `NgModel` instance model value, and queues an async task to set the value for the internal form control instance.
|
||||||
|
1. After the change detection cycle completes, the task to set the form control instance value is called, when then emits the latest value through the `valueChanges` observable.
|
||||||
|
1. The control value accessor updates the form input element in the view with the latest `favoriteColor` value.
|
||||||
|
|
||||||
|
## Form validation
|
||||||
|
|
||||||
|
Validation is an integral part of managing any set of forms. Whether you’re checking for required fields or querying an external API for an existing username, Angular provides a set of built-in validators as well as the ability to create custom validators. With reactive forms, custom validators are functions that receive a control to validate. Because template-driven forms are tied to directives, custom validator directives wrap validation functions to use it in a template.
|
||||||
|
|
||||||
|
For more on form validation, see the [Form Validation](guide/form-validation) guide.
|
||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
|
|
||||||
Testing also plays a large part in complex applications and an easier testing strategy is always welcomed. One big difference in testing reactive forms and template-driven forms is their reliance on rendering the UI in order to perform assertions based on form control and form field changes. The following examples display the process of testing forms with reactive and template-driven forms.
|
Testing also plays a large part in complex applications and an easier testing strategy is always welcomed. One difference in testing reactive forms and template-driven forms is their reliance on rendering the UI in order to perform assertions based on form control and form field changes. The following examples demonstrate the process of testing forms with reactive and template-driven forms.
|
||||||
|
|
||||||
### Testing a reactive form
|
### Testing a reactive form
|
||||||
|
|
||||||
Using the name components mentioned earlier, we test against the same data flows with reactive forms.
|
Reactive forms provide a relatively easy testing strategy to due to synchronous access to the form and data models, and being independent of the UI. In these set of tests, controls and data are queried and manipulated through the control without interacting with the change detection cycle. The following tests below use the favorite color components mentioned earlier to validate the view-to-model and model-to-view data flows for a reactive form.
|
||||||
|
|
||||||
<code-example path="forms-overview/src/app/reactive/name/name.component.spec.ts" region="tests">
|
The following test validates the view-to-model data flow:
|
||||||
|
|
||||||
|
<code-example path="forms-overview/src/app/reactive/favorite-color/favorite-color.component.spec.ts" region="view-to-model" title="Favorite color test (view-to-model)">
|
||||||
</code-example>
|
</code-example>
|
||||||
|
|
||||||
Reactive forms provide a relatively easy testing strategy to due to synchronous access to the form and data models, and being independent of the UI. In these set of tests, controls and data are queried and manipulated easily through the control without interactving with the change detection cycle. We make verify changes predictablity from the form model.
|
1. Query the view for the form input element, and create a custom input event for the test.
|
||||||
|
1. Set the new value for the input is set to *Red*, and dispatch the input event on the form input element.
|
||||||
|
1. Assert that the `favoriteColor` form control instance value matches in value from the input.
|
||||||
|
|
||||||
|
The following test validates the model-to-view data flow:
|
||||||
|
|
||||||
|
<code-example path="forms-overview/src/app/reactive/favorite-color/favorite-color.component.spec.ts" region="model-to-view" title="Favorite color test (model-to-view)">
|
||||||
|
</code-example>
|
||||||
|
|
||||||
|
1. Use the `favoriteColor` form control instance to set the new value.
|
||||||
|
1. Query the view for the form input element.
|
||||||
|
1. Assert that the new value set on the control matches the value in the input.
|
||||||
|
|
||||||
### Testing a template-driven form
|
### Testing a template-driven form
|
||||||
|
|
||||||
Writing tests with template-driven forms is more involved and requires more detailed knowledge of the change detection process and how directives run on each cycle to ensure elements can be queried at the correct time.
|
Writing tests with template-driven forms is more involved and requires more detailed knowledge of the change detection process and how directives run on each cycle to ensure elements are queried, tested, or changed at the correct time. The following tests below use the favorite color components mentioned earlier to validate the view-to-model and model-to-view data flows for a template-driven form.
|
||||||
|
|
||||||
<code-example path="forms-overview/src/app/template/name/name.component.spec.ts" region="tests">
|
The following test validates the view-to-model data flow:
|
||||||
|
|
||||||
|
<code-example path="forms-overview/src/app/template/favorite-color/favorite-color.component.spec.ts" region="view-to-model" title="Favorite color test (view-to-model)">
|
||||||
</code-example>
|
</code-example>
|
||||||
|
|
||||||
Because template-driven are asynchronous, each test must be wrapped in a `fakeAsync` method to simulate queueing of tasks. The `tick` function *must* be used to update the rendered template after detecting changes. You must wait for the appropiate lifecycle hooks to finish before extracting any values, testing its validity or changing the value of a control.
|
1. Query the view for the form input element, and create a custom input event for the test.
|
||||||
|
1. Set the new value for the input is set to *Red*, and dispatch the input event on the form input element.
|
||||||
|
1. Use the `tick()` method to simulate passage of time within the `fakeAsync()` task.
|
||||||
|
1. Assert that the component `favoriteColor` property value matches the value from the input.
|
||||||
|
|
||||||
|
The following test validates the model-to-view data flow:
|
||||||
|
|
||||||
|
<code-example path="forms-overview/src/app/template/favorite-color/favorite-color.component.spec.ts" region="model-to-view" title="Favorite color test (model-to-view)">
|
||||||
|
</code-example>
|
||||||
|
|
||||||
|
1. Use the component instance to set the value of `favoriteColor` property.
|
||||||
|
1. Run change detection through the test fixture.
|
||||||
|
1. Use the `tick()` method to simulate passage of time within the `fakeAsync()` task.
|
||||||
|
1. Query the view for the form input element.
|
||||||
|
1. Assert that the input value matches the `favoriteColor` value property in the component instance.
|
||||||
|
|
||||||
## Mutability
|
## Mutability
|
||||||
|
|
||||||
How changes are tracked plays a role in the efficiency of your application. Reactive forms keep the data model pure by providing it as an immutable data structure. Each time the a change is triggered on the data model, a new data model is returned rather than updating the data model directly. This is more efficient, giving you the ability track unique changes to the data model. It also follows reactive patterns that integrate with observable operators to map and transform data. Template-driven forms rely on mutability with two-way data binding to update the data model in the component as changes are made in the template.
|
How changes are tracked plays a role in the efficiency of your application.
|
||||||
|
|
||||||
|
- Reactive forms keep the data model pure by providing it as an immutable data structure. Each time a change is triggered on the data model, a new data model is returned rather than updating the data model directly. This gives you the ability track unique changes to the data model. It also follows reactive patterns that integrate with observable operators to transform data.
|
||||||
|
- Template-driven forms rely on mutability with two-way data binding to update the data model in the component as changes are made in the template.
|
||||||
|
|
||||||
|
This is demonstrated in the examples above using the **favorite color** input element. With reactive forms, the **form control instance** always returns a new value when the control's value is updated. With template-driven forms, the **favorite color property** is always modified to its new value.
|
||||||
|
|
||||||
## Scalability
|
## Scalability
|
||||||
|
|
||||||
If forms are a central part of your application, scalability is very important. Being able to reuse form models across components and data access is critical. Reactive forms makes creating large scale forms easier by providing access to low-level APIs and synchronous access to the data model. Because template-driven forms focus on simplicity and simple scenarios with static content and little validation, they are not as reusable and abstract away the low-level APIs and access to the data model is handled asynchronously.
|
If forms are a central part of your application, scalability is very important. Being able to reuse form models across components is critical. Reactive forms make creating large scale forms easier by providing access to low-level APIs and synchronous access to the data model. Because template-driven forms focus on simple scenarios with very little validation, they are not as reusable and abstract away the low-level APIs and access to the data model is handled asynchronously.
|
||||||
|
|
||||||
## Next Steps
|
## Next Steps
|
||||||
|
|
||||||
After you understand the two approaches to handling form inputs, you can learn more about common examples and practices using reactive forms or template-driven forms. The following guides are the next steps in the learning process for each approach.
|
You can learn more about common examples and practices using reactive forms or template-driven forms. The following guides are the next steps in the learning process for all.
|
||||||
|
|
||||||
|
To learn more about reactive forms, see the following guides:
|
||||||
|
|
||||||
* [Reactive Forms](guide/reactive-forms)
|
* [Reactive Forms](guide/reactive-forms)
|
||||||
* [Form Validation](guide/form-validation#reactive-form-validation)
|
* [Form Validation](guide/form-validation#reactive-form-validation)
|
||||||
* [Dynamic forms](guide/dynamic-form)
|
* [Dynamic forms](guide/dynamic-form)
|
||||||
|
|
||||||
|
To learn more about tempate-driven forms, see the following guides:
|
||||||
|
|
||||||
* [Template-driven Forms](guide/forms)
|
* [Template-driven Forms](guide/forms)
|
||||||
* [Form Validation](guide/form-validation#template-driven-validation)
|
* [Form Validation](guide/form-validation#template-driven-validation)
|
||||||
|
|
Loading…
Reference in New Issue