Input handling is an important part of application development. The ng-model directive provided in Angular 1 is a great way to manage input, but we think we can do better. The new Angular Forms module is easier to use and reason about than ng-model, it provides the same conveniences as ng-model, but does not have its drawbacks. In this article we will talk about the design goals for the module and show how to use for common use cases.
Optimizing for real world apps
Let's look at what a simple HelloWorld example would look like in Angular 2:
@Component({
selector: 'form-example'
})
@Template({
// we are binding the input element to the control object
// defined in the component's class
inline: `<input [control]="username">Hello {{username.value}}!`,
directives: [forms]
})
class FormExample {
constructor() {
this.username = new Control('World');
}
}
This example is written using TypeScript 1.5 that supports type and metadata annotations, but it can be easily written in ES6 or ES5. You can find more information on annotations
here. The example also uses the new template syntax that you can learn about by watching
the keynote Misko and Rado gave at NgConf.
And, for comparison sake, here's what we'd write in Angular 1:
var module = angular.module("example", []);
module.controller("FormExample", function() {
this.username = "World";
});
<div ng-controller="FormExample as ctrl">
<input ng-model="ctrl.username"> Hello {{ctrl.username}}!
</div>
At the surface Angular 1 example looks simpler that what we have just done in Angular 2. Let's talk about the challenges of Angular 1 approach with real world applications.
- You can not unit test the form behavior without compiling the associated template. This is because the template contains part of the application behavior.
- Though you can do dynamically generated data-driven forms in Angular 1, it is not easy and we want to enable this as a core use case for Angular 2.
- The ng-model directive was built using a generic two-way data-binding which makes it difficult to reason about your template statically. Will go into depth on this topic in a following blog post and describe how it lets us achieve significant performance improvements.
- There was no concept of an atomic form which could easily be validated, or reverted to original state.
Although Angular 2 uses an extra level of indirection, it grants major benefits. The control object decouples form behavior from the template, so that you can test it in isolation. Tests are simpler to write and faster to execute.
Now let's look at a more complex example so that you can see some of these properties.
Forms Mental Model
In Angular 2 working with Forms is broken down to three layers. At the very bottom we can work with HTML elements. On top of that Angular 2 provides the Form Controls API which we have shown in the example above. Finally, Angular 2 will also provide a data-driven forms API which will make building large-scale forms a snap.
Let's look at how this extra level of indirection benefits us for more realistic examples.
Data-Driven Forms
Let's say we would like to build a form such as this:
We will have an object model of an Address which needs to be presented to the user. The requirements also include providing correct layout, labels, and error handling. We would write it like this in Angular 2.
(This is proposed API, we would love to take your input on this.)
import {forms, required, materialDesign} from 'angular2/forms';
// Our model
class Address {
street: string;
city: string;
state: string;
zip: string;
residential: boolean;
}
@Component({
selector: 'form-example'
})
@Template({
// Form layout is automatic from the structure
inline: `<form [form-structure]=”form”></form>`
directives: [forms]
})
class FormExample {
constructor(fb: FormBuilder) {
this.address = new Address();
// defining a form structure and initializing it using
// the passed in model
this.form = fb.fromModel(address, [
// describe the model field, labels and error handling
{field: 'street', label: 'Street', validator: required},
{field: 'city', label: 'City', validator: required},
{field: 'state', label: 'State', size: 2,
validator: required},
{field: 'zip', label: 'Zip', size: 5,
validator: zipCodeValidator},
{field: 'isResidential', type: 'checkbox',
label: 'Is residential'}
}, {
// update the model every time an input changes
saveOnUpdate: true,
// Allow setting different layout strategies
layoutStrategy: materialDesign
});
}
}
function zipCodeValidator(control) {
if (! control.value.match(/\d\d\d\d\d(-\d\d\d\d)?/)){
return {invalidZipCode: true};
}
}
The above example shows how an existing model Address can be turned into a form. The process include describing the fields, labels, and validators in a declarative way in your component. The form HTML structure will be generated automatically based on the layout strategy provided to the builder. This helps keeping consistent look & feel through the application. Finally, it is also possible to control the write through behavior, which allows atomic writes to the model.
We have taken great care to ensure that the forms API is pluggable, allowing you to define custom validators, reuse web-component controls, and define layout and theme.
Form Controls
Although having data driven forms is convenient, sometimes you would like to have full control of how a form is laid out on page. Let's rebuild the same example using the lower level API, which allows you to control the HTML structure in full detail. (This works today in Angular 2 Alpha, but we are also happy to receive your input on improvements we could make.)
import {forms, required} from 'angular2/forms';
// An example of typical model
class Address {
street: string;
city: string;
state: string;
zip: string;
residential: boolean;
}
function zipCodeValidator(control) {
if (! control.value.match(/\d\d\d\d\d(-\d\d\d\d)?/)){
return {invalidZipCode: true};
}
}
@Component({
selector: 'form-example'
})
@Template({
inline: `
// explicitly defining the template of the form
<form [form]=”form”>
Street <input control="street">
<div *if="form.hasError('street', 'required')">Required</div>
City <input control="city">
<div *if="form.hasError('city', 'required')">Required</div>
State <input control="state" size="2">
<div *if="form.hasError('state', 'required')">Required</div>
Zip <input control="zip" size="5">
<div *if="form.hasError('zip', 'invalidZipCoed')">
Zip code is invalid
</div>
Residential <input control="isResidential" type="checkbox">
</form>
`
directives: [forms]
})
class FormExample {
constructor(fb: FormBuilder) {
this.address = new Address();
// defining a form model
this.form = fb.group({
street: [this.address.street, required],
city: [this.address.city, required],
state: [this.address.city, required],
zip: [this.address.zip, zipCodeValidator],
isResidential: [this.address.isResidential]
});
this.form.changes.forEach(() => this.form.writeTo(this.address));
}
}
When using the control form API we still define the behavior of the form in the component, but the way the form is laid out is defined in the template. This allows you to implement even the most unusual forms.
Summary
The new Angular 2 Forms module makes building forms easier than ever. It also adds benefits such as consistent look and feel for all forms in your application, easier unit testing, and more predictable behavior.
- [Angular] Create a custom validator for reactive forms in Angular
Also check: directive for form validation User input validation is a core part of creating proper HT ...
- [Angular] Create a custom validator for template driven forms in Angular
User input validation is a core part of creating proper HTML forms. Form validators not only help yo ...
- 从零开始构建 Wijmo & Angular 2 小应用
中秋之际,Angular 团队发布 Angular 2 正式版,一款不错的图表控件Wijmo当天宣布支持 . Angular 2移除和替代了 Angular 1.X 中的 directives, co ...
- 来自 Thoughtram 的 Angular 2 系列资料
Angular 2 已经正式 Release 了,Thoughtram 已经发布了一系列的文档,对 Angular 2 的各个方面进行深入的阐释和说明. 我计划逐渐将这个系列翻译出来,以便对大家学习 ...
- [Angular2 Form] Create and Submit an Angular 2 Form using ngForm
Forms in Angular 2 are essentially wrappers around inputs that group the input values together into ...
- Wijmo Angular 2 小应用
Wijmo & Angular 2 小应用 中秋之际,Angular 团队发布 Angular 2 正式版,一款不错的图表控件Wijmo当天宣布支持 . Angular 2移除和替代了 Ang ...
- [AngularJS] Isolate State Mutations in Angular Components
Managing state is one of the hardest things to do in any application. Angular 2 tackles this problem ...
- 支持Angular 2的表格控件
前端框架一直这最近几年特别火的一个话题,尤其是Angular 2拥有众多的粉丝.在2016年9月份Angular 2正式发布之后,大量的粉丝的开始投入到了Angular 2的怀抱.当然这其中也包括我. ...
- Angular 2的表格控件
Angular 2的表格控件 前端框架一直这最近几年特别火的一个话题,尤其是Angular 2拥有众多的粉丝.在2016年9月份Angular 2正式发布之后,大量的粉丝的开始投入到了Angular ...
随机推荐
- [BZOJ2727][HNOI2012]双十字
bzoj luogu sol 先预处理从每个点出发向上/下/左/右能延伸多长. 考虑怎么计算答案.我们只要枚举中轴线,再枚举上方的十字交点,枚举下方的十字交点,然后算答案即可. 考虑一个左右宽的最小值 ...
- python try except, 异常处理
http://www.runoob.com/python/python-exceptions.html http://blog.sciencenet.cn/blog-3031432-1059523.h ...
- Python中定时任务框架APScheduler
前言 大家应该都知道在编程语言中,定时任务是常用的一种调度形式,在Python中也涌现了非常多的调度模块,本文将简要介绍APScheduler的基本使用方法. 一.APScheduler介绍 APSc ...
- ballerina 学习二十五 项目docker 部署&& 运行
ballerina 官方提供了docker 的runtime,还是比较方便的 基本项目创建 使用cli创建项目 按照提示操作就行 ballerina init -i 项目结构 添加了dockerfil ...
- p/Invoke工具
开源的工具 下面这个链接来下载这个工具: http://download.microsoft.com/download/f/2/7/f279e71e-efb0-4155-873d-5554a06085 ...
- Oracle单表去重复(一)
去重有两层含义,一:是记录完全一样:二:是符合一定条件的认为是重复. 根据表的数量,去重可划分为:单表去重和多表关联去重. 对于去重,一般最容易想到的是用distinct,而distinct只能对 ...
- Spring Boot 报错:Error creating bean with name 'entityManagerFactory' defined in class path resource
spring boot 写一个web项目,在使用spring-data-jpa的时候,启动报如下错误: Error starting ApplicationContext. To display th ...
- 【转】VC++10(VS2010)IDE各种使用技巧
原文网址:http://www.cnblogs.com/sunrisezhang/articles/2802397.html 一个好的coder,他首先必须是一个熟练工.对于C++程序员来说,只有掌握 ...
- 查询反模式 - GroupBy和HAVING的理解
为了最简单地说明问题,我特地设计了一张这样的表. 一.GROUP BY单值规则 规则1:单值规则,跟在SELECT后面的列表,对于每个分组来说,必须返回且仅仅返回一个值. 典型的表现就是跟在SELEC ...
- Mysql root 用户密码忘记后重置root密码
[windows] 1.停止mysql服务:打开命令行窗口CMD,Net stop mysql 2.用另外一种方式启动Mysql:在命令行进入到mysql的安装路径下的bin目录下使用 mysqld- ...