include ../_util-fns :marked We’ve all used a form to login, submit a help request, place an order, book a flight, schedule a meeting and perform countless other data entry tasks. Forms are the mainstay of business applications. 我们全都用过表单来执行登录、求助、下单、预订机票、发起会议,以及不计其数的其它数据录入任务。 表单是商业应用的主体。 Any seasoned web developer can slap together an HTML form with all the right tags. It's more challenging to create a cohesive data entry experience that guides the user efficiently and effectively through the workflow behind the form. 不管什么样的Web开发者,都能使用正确的标签“捏”出一个HTML。 但要想做出一个优秀的表单,让它具有贴心的数据输入体验,以指导用户明晰、高效的通过表单完成背后的工作流程,这个挑战就大多了。 *That* takes design skills that are, to be frank, well out of scope for this chapter. *这当中*所需要的设计技能,坦白讲,确实超出了本章的范围。 It also takes framework support for **two-way data binding, change tracking, validation, and error handling** ... which we shall cover in this chapter on Angular forms. 但它也需要框架支持,来实现**双向数据绑定、变更跟踪、有效性验证和错误处理**…… 这些Angular表单相关的内容,属于本章的范围。 We will build a simple form from scratch, one step at a time. Along the way we'll learn 我们将从零构建一个简单的表单,把它简化到一次一步。通过这种方式,我们将学到: - to build an Angular form with a component and template - 使用组件和模板构建一个Angular表单 - two-way data binding with `[(ngModel)]` syntax for reading and writing values to input controls - 使用`[(ngModel)]`语法实现双向数据绑定,以便于读取和写入输入控件的值 - using `ngControl` to track the change state and validity of form controls - 使用`ngControl`来跟踪变更状态并对表单控件做验证 - the special CSS classes that `ngControl` adds to form controls and how we can use them to provide strong visual feedback - `ngControl`添加到表单控件上的那些特殊的CSS类,以及我们该如何使用它们来提供强烈的视觉反馈 - displaying validation errors to users and enable/disable form controls - 向用户显示有效性验证的错误提示,以及禁用/启用表单控件 - sharing information among controls with template reference variables - 通过模板引用变量,在控件之间共享信息 [Live Example](/resources/live-examples/forms/ts/plnkr.html) [在线例子](/resources/live-examples/forms/ts/plnkr.html) .l-main-section :marked ## Template-Driven Forms ## 模板驱动的表单 Many of us will build forms by writing templates in the Angular [template syntax](./template-syntax.html) with the form-specific directives and techniques described in this chapter. 我们大多数都可以使用表单特有的指令和本章所描述的技术,在模板中按照Angular[模板语法](./template-syntax.html)来构建表单。 .l-sub-section :marked That's not the only way to create a form but it's the way we'll cover in this chapter. 这不是创建表单的唯一方式,但它是我们将在本章中使用的方式。 :marked We can build almost any form we need with an Angular template — login forms, contact forms ... pretty much any business forms. We can lay out the controls creatively, bind them to data, specify validation rules and display validation errors, conditionally enable or disable specific controls, trigger built-in visual feedback, and much more. 我们可以构建要用在Angular模板中的几乎所有表单 —— 登录表单、联系人表单…… 大量的各种商务表单。 我们可以创造性的摆放各种控件、把它们绑定到数据、指定校验规则、显示校验错误、有条件的禁用/启用特定的控件、触发内置的视觉反馈等等,不胜枚举。 It will be pretty easy because Angular handles many of the repetitive, boiler plate tasks we'd otherwise wrestle with ourselves. 它的确很简单,这是因为Angular帮我们处理了大多数重复、单调的任务,这让我们可以不必亲自操刀、身陷其中。 We'll discuss and learn to build the following template-driven form: 我们将讨论和学习构建如下的“模板驱动”表单: figure.image-display img(src="/resources/images/devguide/forms/hero-form-1.png" width="400px" alt="Clean Form") :marked Here at the *Hero Employment Agency* we use this form to maintain personal information about the heroes in our stable. Every hero needs a job. It's our company mission to match the right hero with the right crisis! 这里是*英雄职介中心*,我们使用这个表单来维护我们候选英雄们的个人信息。每个英雄都需要一份工作。我们公司的任务就是让正确的英雄去解决他/她所擅长应对的危机! Two of the three fields on this form are required. Required fields have a green bar on the left to make them easy to spot. 这个表单中的三个字段都是必填的。这些必填的字段在左侧会有一个绿色的条儿,让它们更容易看出来。 If we delete the hero name, the form displays a validation error in an attention grabbing style: 如果我们删除了英雄的名字,表单就会用一种引人注目的样式把验证错误显示出来。 figure.image-display img(src="/resources/images/devguide/forms/hero-form-2.png" width="400px" alt="无效!名字是必填项") :marked Note that the submit button is disabled and the "required" bar to the left of the input control changed from green to red. 注意,提交按钮被禁用了,而且输入控件左侧的“必填”条从绿色变为了红色。 .l-sub-section p We'll customize the colors and location of the "required" bar with standard CSS. p 我们将使用标准CSS来定制“必填”条的颜色和位置。 :marked We will build this form in the following sequence of small steps 我们将按照一系列很小的步骤来构建此表单: 1. Create the `Hero` model class 1. 创建`Hero`模型类 1. Create the component that controls the form 1. 创建控制此表单的组件 1. Create a template with the initial form layout 1. 创建具有初始表单布局的模板 1. Bind data properties to each form input control with the `ngModel` two-way data binding syntax 1. 使用`ngModel`双向数据绑定语法把数据属性绑定到每个表单输入控件 1. Add the **ngControl** directive to each form input control 1. 往每个表单输入控件上添加**ngControl**指令 1. Add custom CSS to provide visual feedback 1. 添加自定义CSS来提供视觉反馈 1. Show and hide validation error messages 1. 显示和隐藏有效性验证的错误信息 1. Handle form submission with **ngSubmit** 1. 使用**ngSubmit**处理表单提交 1. Disable the form’s submit button until the form is valid 1. 禁用此表单的提交按钮,直到表单变为有效的 :marked ## Setup ## 起步 Create a new project folder (`angular2-forms`) and follow the steps in the [QuickStart](../quickstart.html). 创建一个新的项目文件夹(`angular2-forms`),并且完成[“快速起步”](../quickstart.html)中的步骤。 include ../_quickstart_repo :marked ## Create the Hero Model Class ## 创建一个Hero模型类 As users enter form data, we capture their changes and update an instance of a model. We can't layout the form until we know what the model looks like. 当用户输入表单数据时,我们要捕获他们的变化,并更新到模型的一个实例中。 除非我们知道模型里有什么,否则没法设计表单。 A model can be as simple as a "property bag" that holds facts about a thing of application importance. That describes well our `Hero` class with its three required fields (`id`, `name`, `power`) and one optional field (`alterEgo`). 最简单的模型就是一个“属性包”,用来存放关于应用中一件重要事物的某些事实。 这里我们使用三个必备字段(`id`、`name`、`power`),和一个可选字段(`alterEgo`,译注:中文含义:第二人格,比如X战警中的Jean/黑凤凰)。 Create a new file in the app folder called `hero.ts` and give it the following class definition: 在应用文件夹中创建一个`hero.ts`文件,并且写入下列类定义内容: +makeExample('forms/ts/app/hero.ts', null, 'app/hero.ts') :marked It's an anemic model with few requirements and no behavior. Perfect for our demo. 这是一个贫血模型,没什么要求,也没有行为。对我们的演示来说很完美。 The TypeScript compiler generates a public field for each `public` constructor parameter and assigns the parameter’s value to that field automatically when we create new heroes. TypeScript编译器为构造函数中每个标为`public`的参数创建一个公有字段,并在创建新的英雄实例时,把参数值自动赋给这些公有字段。 The `alterEgo` is optional and the constructor lets us omit it; note the (?) in `alterEgo?`. `alterEgo`是可选的,构造函数让我们可以省略掉它,注意`alterEgo?`中的问号(?)。 We can create a new hero like this: 我们可以像这样创建一个新英雄: code-example(format=""). let myHero = new Hero(42, 'SkyDog', 'Fetch any object at any distance', 'Leslie Rollover'); console.log('My hero is called ' + myHero.name); // "My hero is called SkyDog" :marked .l-main-section :marked ## Create a Form component ## 创建一个表单组件 An Angular form has two parts: an HTML-based template and a code-based Component to handle data and user interactions. 每个Angular表单分为两部分:一个基于HTML的模板,和一个基于代码的组件,它用来处理数据和用户交互。 We begin with the Component because it states, in brief, what the Hero editor can do. 我们从组件开始,是因为它能够简要说明英雄编辑器能做什么。 Create a new file called `hero-form.component.ts` and give it the following definition: 创建一个名叫`hero-form.component.ts`的文件,并且放进下列定义: +makeExample('forms/ts/app/hero-form.component.ts', 'first', 'app/hero-form.component.ts') :marked There’s nothing special about this component, nothing form-specific, nothing to distinguish it from any component we've written before. 本组件没有什么特别的地方:没有表单相关的东西,也没有任何地方能把它和我们以前写过的那些组件区分开。 Understanding this component requires only the Angular 2 concepts we’ve learned in previous chapters 要理解这个组件,只会用到前面章节中已经学过的那些概念: 1. We import the `Component` decorator from the Angular library as we usually do. 1. 像往常一样,我们从Angular库中导入`Component`装饰器。 1. The `@Component` selector value of "hero-form" means we can drop this form in a parent template with a `` tag. 1. `@Component`选择器的值"hero-form"表示我们将把此表单扔进父模板中的一个``标签中。 1. The `templateUrl` property points to a separate file for template HTML called `hero-form.component.html`. 1. `templateUrl`属性指向一个独立的HTML模板文件,名叫`hero-form.component.html`。 1. We defined dummy data for `model` and `powers` as befits a demo. Down the road, we can inject a data service to get and save real data or perhaps expose these properties as [inputs and outputs](./template-syntax.html#inputs-outputs) for binding to a parent component. None of this concerns us now and these future changes won't affect our form. 1. 我们为`model`和`powers`定义了供演示用的假数据。 接下来,我们可以注入一个用于获取和保存真实数据的服务, 或者把这些属性暴露为[输入与输出属性](./template-syntax.html#inputs-outputs),以绑定到父组件上。 我们目前不关心这些,因为将来这些变化不会影响到我们的表单。 1. We threw in a `diagnostic` property at the end to return a JSON representation of our model. It'll help us see what we're doing during our development; we've left ourselves a cleanup note to discard it later. 1. 我们在最后增加一个`diagnostic`属性,它返回这个模型的JSON形式。 它会帮我们看清开发过程中发生的事,等最后做清理时我们会丢弃它。 Why don't we write the template inline in the component file as we often do elsewhere in the Developer Guide? 这次我们为什么不像开发人员指南中的其它地方那样写成组件的内联模板呢? There is no “right” answer for all occasions. We like inline templates when they are short. Most form templates won't be short. TypeScript and JavaScript files generally aren't the best place to write (or read) large stretches of HTML and few editors are much help with files that have a mix of HTML and code. We also like short files with a clear and obvious purpose like this one. 没有什么答案在所有场合都总是“正确”的。当内联模板足够短的时候,我们更喜欢用它。 但大多数的表单模板都不短。普遍来讲,TypeScript和JavaScript文件不会是写大型HTML的好地方(也不好读)。 而且没有几个编辑器能对混写的HTML和代码提供足够的帮助。 我们还是喜欢写成像这个一样清晰明确的短文件。 We made a good choice to put the HTML template elsewhere. We'll write that template in a moment. Before we do, we'll take a step back and revise the `app.component.ts` to make use of our new `HeroFormComponent`. 把HTML模板放在别处是一个好的选择。 我们一会儿就去写那个模板。在这之前,我们先回来修改`app.component.ts`文件,来让它用上我们新的`HeroFormComponent`组件。 .l-main-section :marked ## Revise the *app.component.ts* ## 修改*app.component.ts*文件 `app.component.ts` is the application's root component. It will host our new `HeroFormComponent`. `app.component.ts`是本应用的根组件,我们的`HeroFormComponent`将放在其中。 Replace the contents of the "QuickStart" version with the following: 把"快速起步"的版本内容替换成下列代码: +makeExample('forms/ts/app/app.component.ts', null, 'app/app.component.ts') :marked .l-sub-section :marked There are only three changes: 只有三处修改: 1. We import the new `HeroFormComponent`. 1. 导入了新的`HeroFormComponent`组件。 1. The `template` is simply the new element tag identified by the component's `selector` property. 1. 直接把`template`的内容改成`HeroFormComponent`的`selector`属性中指定的新元素标签。 1. The `directives` array tells Angular that our template depends upon the `HeroFormComponent` which is itself a Directive (as are all Components). 1. `directives`数组告诉Angular,我们的模板依赖于`HeroFormComponent`组件,它本身也是一个指令(所有组件都是指令)。 .l-main-section :marked ## Create an initial HTML Form Template ## 创建一个初始的HTML表单模板 Create a new template file called `hero-form.component.html` and give it the following definition: 创建一个新的模板文件,命名为`hero-form.component.html`,并且填写如下内容: +makeExample('forms/ts/app/hero-form.component.html', 'start', 'app/hero-form.component.html') :marked That is plain old HTML 5. We're presenting two of the `Hero` fields, `name` and `alterEgo`, and opening them up for user input in input boxes. 这只是一段普通的旧式HTML 5代码。这里出现了两个`Hero`字段,`name`和`alterEgo`,让用户可以在输入框中输入,修改他们。 The *Name* `` control has the HTML5 `required` attribute; the *Alter Ego* `` control does not because `alterEgo` is optional. *Name*``控件具有HTML5的`required`属性;但 *Alter Ego* ``控件没有,因为`alterEgo`字段是可选的。 We've got a *Submit* button at the bottom with some classes on it. 我们在底部有一个*Submit*按钮,它有一些CSS类。 **We are not using Angular yet**. There are no bindings. No extra directives. Just layout. **我们还没有用到Angular**。没有绑定。没有额外的指令。只做了个布局。 The `container`,`form-group`, `form-control`, and `btn` classes come from [Twitter Bootstrap](http://getbootstrap.com/css/). Purely cosmetic. We're using Bootstrap to gussy up our form. Hey, what's a form without a little style! `container`、`form-group`、`form-control`和`btn`类来自[Twitter Bootstrap](http://getbootstrap.com/css/)。纯粹是装饰。 我们使用Bootstrap来打扮我们的表单。 嘿,一点儿样式儿都没有的表单算个啥! .callout.is-important header Angular Forms Do Not Require A Style Library header Angular表单不需要任何样式库 :marked Angular makes no use of the `container`, `form-group`, `form-control`, and `btn` classes or the styles of any external library. Angular apps can use any CSS library ... or none at all. Angular不需要`container`、`form-group`、`form-control`和`btn`类,或者来自任何第三方库的任何样式,Angular应用可以使用任何CSS库 …… 或者啥都不用。 :marked Let's add the stylesheet. 我们来添加样式表。 ol li Open a terminal window in the application root folder and enter the command: li 在应用的根目录下打开一个终端窗口,敲如下命令: code-example(language="html" escape="html"). npm install bootstrap --save li Open index.html and add the following link to the <head>. li 打开index.html文件并且把下列链接添加到<head>中。 +makeExample('forms/ts/index.html', 'bootstrap')(format=".") :marked .l-main-section :marked ## Add Powers with ***ngFor** ## 用***ngFor***添加超能力 Our hero may choose one super power from a fixed list of Agency-approved powers. We maintain that list internally (in `HeroFormComponent`). 我们的英雄可以从由职介中心认证过的固定列表中选择一项超能力。 我们先在`HeroFormComponent`中内部维护这个列表。 We'll add a `select` to our form and bind the options to the `powers` list using `ngFor`, a technique we might have seen before in the [Displaying Data](./displaying-data.html) chapter. 我们将添加一个`select`到表单中,并且用`ngFor`把`powers`列表绑定到`option`中。 前面我们应该在[显示数据](./displaying-data.html)一章中见过`ngFor`。 Add the following HTML *immediately below* the *Alter Ego* group. 在*Alter Ego*的紧下方添加如下HTML: +makeExample('forms/ts/app/hero-form.component.html', 'powers', 'app/hero-form.component.html (节选)')(format=".") :marked We are repeating the `` tag for each power in the list of Powers. The `p` template input variable is a different power in each iteration; we display its name using the interpolation syntax with the double-curly-braces. 我们为列表中的每一项超能力渲染出一个`