include ../_util-fns :marked We’ve all used a form to log in, 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 how to 我们将从零构建一个简单的表单,把它简化到一次一步。通过这种方式,我们将学到如何: - build an Angular form with a component and template - 使用组件和模板构建一个Angular表单 - two-way data bind with `[(ngModel)]` syntax for reading and writing values to input controls - 使用`[(ngModel)]`语法实现双向数据绑定,以便于读取和写入输入控件的值 - track the change state and validity of form controls using `ngModel` in combination with a form - 结合表单来使用`ngModel`,能让我们跟踪状态的变化并对表单控件做验证 - provide strong visual feedback using special CSS classes that track the state of the controls - 使用特殊的CSS类来跟踪控件状态,并提供强烈的视觉反馈 - display validation errors to users and enable/disable form controls - 向用户显示有效性验证的错误提示,以及禁用/启用表单控件 - use [template reference variables](./template-syntax.html#ref-vars) for sharing information among HTML elements - 通过模板引用变量,在控件之间共享信息 Run the . 运行在线例子 .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. 这不是创建表单的唯一方式,但它是我们将在本章中使用的方式。(译注:Angular支持的另一种方式叫做模型驱动表单Model-Driven Forms) :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 `name` attribute to each form input control 1. 往每个表单输入控件上添加`name`属性(Attribute) 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 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. We import the `Hero` model we just created. 1. 导入刚刚创建的`Hero`模型 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 the 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.module.ts` and `app.component.ts` to make use of our new `HeroFormComponent`. 把HTML模板放在别处是一个好的选择。 我们一会儿就去写那个模板。在这之前,我们先回来修改`app.module.ts`和`app.component.ts`文件,来让它用上我们新的`HeroFormComponent`组件。 .l-main-section :marked ## Revise the *app.module.ts* ## 修改 *app.module.ts** `app.module.ts` defines the application's root module. In it we identify the external modules we'll use in our application and declare the components that belong to this module, such as our `HeroFormComponent`. `app.module.ts`定义了应用的根模块。在那里,我们指出了即将用到的外部模块,并且声明了属于本模块中的组件,比如`HeroFormComponent`。 Because template-driven forms are in their own module, we need to add the `FormsModule` to the array of `imports` for our application module before we can use forms. 因为模板驱动的表单有它们自己的模块,所以我们得把`FormsModule`添加到本应用的`imports`数组中,这样我们才能使用表单。 Replace the contents of the "QuickStart" version with the following: 把“快速起步”版的文件替换为如下内容: +makeExample('forms/ts/app/app.module.ts', null, 'app/app.module.ts') :marked .l-sub-section :marked There are three changes: 有三处更改: 1. We import `FormsModule` and our new `HeroFormComponent`. 1. 我们导入了`FormsModule`以及新组件`HeroFormComponent`。 1. We add the `FormsModule` to the list of `imports` defined in the `ngModule` decorator. This gives our application access to all of the template-driven forms features, including `ngModel`. 1. 我们把`FormsModule`添加到`ngModule`装饰器的`imports`列表中。这会让我们的应用能使用模板驱动表单的所有特性,包括`ngModel`。 1. We add the `HeroFormComponent` to the list of `declarations` defined in the `ngModule` decorator. This makes the `HeroFormComponent` component visible throughout this module. 1. 我们把`HeroFormComponent`添加到`ngModule`装饰器的`declarations`列表中。这让`HeroFormComponent`组件在本模块中随处都可访问。 .alert.is-important :marked If a component, directive, or pipe belongs to a module in the `imports` array, _DON'T_ declare it in the `declarations` array. If you wrote it and it should belong to this module, _DO_ declare it in the `declarations` array. 如果一个组件、指令或管道出现在模块的`imports`数组中,就说明它是外来模块,_不要_再到`declarations`数组中声明它们。 如果你自己写的它,并且它属于当前模块,_就要_把它声明在`declarations`数组中。 .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 is only one changes: 仅有的一处修改是: 1. The `template` is simply the new element tag identified by the component's `selector` property. This will display the hero form when the application component is loaded. 1. 直接把`template`的内容改成`HeroFormComponent`的`selector`属性中指定的新元素标签。 于是当应用组件被加载时,将显示这个英雄表单。 .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 for styling. 我们在底部有一个*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. 我们为列表中的每一项超能力渲染出一个`