非常教程

AngularJS参考手册

表单

响应式表单

响应式表单提供了一种模型驱动的方式来处理表单输入,其中的值会随时间而变化。本文会向你展示如何创建和更新单个表单控件,然后在一个分组中使用多个控件,验证表单的值,以及如何实现更高级的表单。

试试响应式表单的在线例子 / 下载范例。

响应式表单简介

响应式表单使用显式的、不可变的方式,管理表单在特定的时间点上的状态。对表单状态的每一次变更都会返回一个新的状态,这样可以在变化时维护模型的整体性。响应式表单是围绕 Observable 的流构建的,表单的输入和值都是通过这些输入值组成的流来提供的,同时,也赋予你对数据进行同步访问的能力。这种方式允许你的模板利用这些表单的“状态变更流”,而不必依赖它们。

响应式表单还让你能更简单的进行测试,因为在请求的那一刻你可以确信这些数据是一致的、可预料的。模板之外的消费方也可以访问同样的流,它们可以安全地操纵这些数据。

响应式表单与模板驱动的表单有着显著的不同点。响应式表单通过对数据模型的同步访问提供了更多的可预测性,使用 Observable 的操作符提供了不可变性,并且通过 Observable 流提供了变化追踪功能。 如果你更喜欢在模板中直接访问数据,那么模板驱动的表单会显得更明确,因为它们依赖嵌入到模板中的指令,并借助可变数据来异步跟踪变化。参见附录来了解这两种范式之间的详细比较。

快速起步

本节描述了添加单个表单控件的一些关键步骤。这里的例子允许用户在输入框中输入自己的名字,捕获输入的值,并把表单控件元素的当前值显示出来。

步骤 1 - 注册 ReactiveFormsModule

要使用响应式表单,就要从 @angular/forms 包中导入 ReactiveFormsModule 并把它添加到你的 NgModule 的 imports 数组中。

src/app/app.module.ts (excerpt)

content_copyimport { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // other imports ...
    ReactiveFormsModule
  ],
})
export class AppModule { }

步骤 2 - 导入并创建一个新的表单控件

为该控件生成一个组件。

content_copyng generate component NameEditor

当使用响应式表单时,FormControl 是最基本的构造块。要注册单个的表单控件,请在组件中导入 FormControl 类,并创建一个 FormControl 的新实例,把它保存在类的某个属性中。

src/app/name-editor/name-editor.component.ts

content_copyimport { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-name-editor',
  templateUrl: './name-editor.component.html',
  styleUrls: ['./name-editor.component.css']
})
export class NameEditorComponent {
  name = new FormControl('');
}

FormControl 的构造函数可以设置初始值,这个例子中它是空字符串。通过在你的组件类中创建这些控件,你可以直接对表单控件的状态进行监听、修改和校验。

步骤 3 - 在模板中注册该控件

在组件类中创建了控件之后,你还要把它和模板中的一个表单控件关联起来。修改模板,为表单控件添加 formControl 绑定,formControl 是由 ReactiveFormsModule 中的 FormControlDirective 提供的。

src/app/name-editor/name-editor.component.html

content_copy<label>
  Name:
  <input type="text" [formControl]="name">
</label>

注意:要了解 ReactiveFormsModule 提供的更多类和指令,请参见 响应式表单 API 一节。

使用这种模板绑定语法,把该表单控件注册给了模板中名为 name 的输入元素。这样,表单控件和 DOM 元素就可以互相通讯了:视图会反映模型的变化,模型也会反映视图中的变化。

显示组件

一旦把该组件添加到模板中,指派给 nameFormControl 就会显示出来。

src/app/app.component.html (name editor)

content_copy<app-name-editor></app-name-editor>

响应式表单

管理控件的值

响应式表单让你可以访问表单控件此刻的状态和值。你可以通过组件类或组件模板来操纵其当前状态和值。下面的例子会显示及修改 FormConrol的值。

显示控件的值

每个 FormControl 都会通过一个名叫 valueChanges 的 Observable 型属性提供它的当前值。你可以在模板中使用 AsyncPipe 来监听模板中表单值的变化,或者在组件类中使用 subscribe() 方法来监听。value 属性也可以给你提供当前值的一个快照。

可以在模板中使用插值表达式来显示当前值,代码如下:

src/app/name-editor/name-editor.component.html (control value)

content_copy<p>
  Value: {{ name.value }}
</p>

一旦你修改了表单控件所关联的元素,这里显示的值也跟着变化了。

响应式表单还能通过每个实例的属性和方法提供关于特定控件的更多信息。AbstractControl 的这些属性和方法用于控制表单状态,并在处理表单校验时决定何时显示信息。 欲知详情,参见稍后的简单表单验证一节。

要了解 FormControl 的其它属性和方法,参见响应式表单 API一节。

替换表单控件的值

响应式表单还有一些方法可以用编程的方式修改控件的值,它让你可以灵活的修改控件的值而不需要借助用户交互。FormControl 提供了一个 setValue() 方法,它会修改这个表单控件的值,并且验证与控件结构相对应的值的结构。比如,当从后端 API 或服务接收到了表单数据时,可以通过 setValue() 方法来把原来的值替换为新的值。

下列的例子往组件类中添加了一个方法,它使用 setValue() 方法来修改 Nancy 控件的值。

src/app/name-editor/name-editor.component.ts (update value)

content_copyupdateName() {
  this.name.setValue('Nancy');
}

修改模板,添加一个按钮,用于模拟改名操作。在点 Update Name 按钮之前表单控件元素中输入的任何值都会回显为它的当前值。

src/app/name-editor/name-editor.component.html (update value)

content_copy<p>
  <button (click)="updateName()">Update Name</button>
</p>

由于表单模型中才是该控件真正的源头,因此当你单击该按钮时,组件中该输入框的值也变化了,覆盖掉它的当前值。

响应式表单

注意:在这个例子中,你只使用单个控件,但是当调用 FormGroupFormArraysetValue() 方法时,传入的值就必须匹配控件组或控件数组的结构才行。

把表单控件分组

正如 FormControl 的实例能让你控制单个输入框所对应的控件,FormGroup 可以跟踪一组 FormControl 实例(比如一个表单)的表单状态。当创建 FormGroup 时,其中的每个控件都会根据其名字进行跟踪。下列例子展示了如何管理单个控件组中的多个 FormControl 实例。

生成一个 ProfileEditor 组件并从 @angular/forms 包中导入 FormGroupFormControl 类。

content_copyng generate component ProfileEditor

src/app/profile-editor/profile-editor.component.ts (imports)

content_copyimport { FormGroup, FormControl } from '@angular/forms';

步骤 1 - 创建 FormGroup

在组件类中创建一个名叫 profileForm 的属性,并设置为 FormGroup 的一个新实例。要初始化这个 FormGroup,请为构造函数提供一个由控件组成的对象,对象中的每个名字都要和表单控件的名字一一对应。

对此个人档案表单,要添加两个 FormControl 实例,名字分别为 firstNamelastName

src/app/profile-editor/profile-editor.component.ts (form group)

content_copyimport { Component } from '@angular/core';import { FormGroup, FormControl } from '@angular/forms'; @Component({  selector: 'app-profile-editor',  templateUrl: './profile-editor.component.html',  styleUrls: ['./profile-editor.component.css']})export class ProfileEditorComponent {  profileForm = new FormGroup({    firstName: new FormControl(''),    lastName: new FormControl(''),  });}

现在,这些独立的表单控件被收集到了一个控件组中。这个 FormGroup 用对象的形式提供了它的模型值,这个值来自组中每个控件的值。FormGroup 实例拥有和 FormControl 实例相同的属性(比如 valueuntouched)和方法(比如 setValue())。

步骤 2 - 关联 FormGroup 的模型和视图

这个 FormGroup 还能跟踪其中每个控件的状态及其变化,所以如果其中的某个控件的状态或值变化了,父控件也会发出一次新的状态变更或值变更事件。该控件组的模型来自它的所有成员。在定义了这个模型之后,你必须更新模板,来把该模型反映到视图中。

src/app/profile-editor/profile-editor.component.html (template form group)

content_copy<form [formGroup]="profileForm">
  
  <label>
    First Name:
    <input type="text" formControlName="firstName">
  </label>

  <label>
    Last Name:
    <input type="text" formControlName="lastName">
  </label>

</form>

注意,就像 FormGroup 所包含的那控件一样,profileForm 这个 FormGroup 也通过 FormGroup 指令绑定到了 form 元素,在该模型和表单中的输入框之间创建了一个通讯层。 由 FormControlName 指令提供的 formControlName 属性把每个输入框和 FormGroup 中定义的表单控件绑定起来。这些表单控件会和相应的元素通讯,它们还把更改传递给 FormGroup,这个 FormGroup 是模型值的真正源头。

保存表单数据

ProfileEditor 组件从用户那里获得输入,但在真实的场景中,你可能想要先捕获表单的值,等将来在组件外部进行处理。 FormGroup 指令会监听 form 元素发出的 submit 事件,并发出一个 ngSubmit 事件,让你可以绑定一个回调函数。

onSubmit() 回调方法添加为 form 标签上的 ngSubmit 事件监听器。

src/app/profile-editor/profile-editor.component.html (submit event)

content_copy<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">

ProfileEditor 组件上的 onSubmit() 方法会捕获 profileForm 的当前值。要保持该表单的封装性,就要使用 EventEmitter 向组件外部提供该表单的值。下面的例子会使用 console.warn 把这个值记录到浏览器的控制台中。

src/app/profile-editor/profile-editor.component.ts (submit method)

content_copyonSubmit() {
  // TODO: Use EventEmitter with form value
  console.warn(this.profileForm.value);
}

form 标签所发出的 submit 事件是原生 DOM 事件,通过点击类型为 submit 的按钮可以触发本事件。这还让用户可以在填写完表单之后使用回车键来触发提交。

往表单的底部添加一个 button,用于触发表单提交。

src/app/profile-editor/profile-editor.component.html (submit button)

content_copy<button type="submit" [disabled]="!profileForm.valid">Submit</button>

注意:上面这个代码片段中的按钮还附加了一个 disabled 绑定,用于在 profileForm 无效时禁用该按钮。目前你还没有执行任何表单验证逻辑,因此该按钮始终是可用的。稍后的表单验证一节会讲解简单的表单验证。

显示组件

当添加到组件模板中时,ProfileEditor 组件所包含的表单就显示出来了。

src/app/app.component.html (profile editor)

content_copy<app-profile-editor></app-profile-editor>

ProfileEditor 让你能管理 FormGroup 中的 firstNamelastNameFormControl 实例。

响应式表单

嵌套的表单组

如果要构建复杂的表单,如果能在更小的分区中管理不同类别的信息就会更容易一些,而有些信息分组可能会自然的汇入另一个更大的组中。使用嵌套的 FormGroup 可以让你把大型表单组织成一些稍小的、易管理的分组。

步骤 1 - 创建嵌套的分组

“地址”就是可以把信息进行分组的绝佳范例。FormGroup 可以同时接纳 FormControlFormGroup 作为子控件。这使得那些比较复杂的表单模型可以更易于维护、更有逻辑性。要想在 profileForm 中创建一个嵌套的分组,请添加一个内嵌的名叫 addressFormGroup

src/app/profile-editor/profile-editor.component.ts (nested form group)

content_copyimport { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-profile-editor',
  templateUrl: './profile-editor.component.html',
  styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
  profileForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    address: new FormGroup({
      street: new FormControl(''),
      city: new FormControl(''),
      state: new FormControl(''),
      zip: new FormControl('')
    })
  });
}

在这个例子中,address group 把现有的 firstNamelastName 控件和新的 streetcitystatezip 控件组合在一起。虽然 address 这个 FormGroupprofileForm 这个整体 FormGroup 的一个子控件,但是仍然适用同样的值和状态的变更规则。来自内嵌控件组的状态和值的变更将会冒泡到它的父控件组,以维护整体模型的一致性。

步骤 2 - 在模板中分组内嵌的表单

在修改了组件类中的模型之后,还要修改模板,来把这个 FormGroup 实例对接到它的输入元素。

把包含 firstNamelastName 字段的 address 表单组添加到 ProfileEditor 模板中。

src/app/profile-editor/profile-editor.component.html (template nested form group)

content_copy<div formGroupName="address">
  <h3>Address</h3>

  <label>
    Street:
    <input type="text" formControlName="street">
  </label>

  <label>
    City:
    <input type="text" formControlName="city">
  </label>
  
  <label>
    State:
    <input type="text" formControlName="state">
  </label>

  <label>
    Zip Code:
    <input type="text" formControlName="zip">
  </label>
</div>

ProfileEditor 表单显示为一个组,但是将来这个模型会被进一步细分,以表示逻辑分组区域。

响应式表单

注意:这里使用了 value 属性和 JsonPipe 管道在组件模板中显示了这个 FormGroup 的值。

部分模型更新

当修改包含多个控件的 FormGroup 的值时,你可能只希望更新模型中的一部分,而不是完全替换掉。这一节会讲解该如何更新 AbstractControl模型中的一部分。

修补(Patch)模型值

对单个控件,你会使用 setValue() 方法来该控件设置新值。但当应用到 FormGroup 并打算整体设置该控件的值时,setValue() 方法会受到这个 FormGroup 结构的很多约束。patchValue() 方法就宽松多了,它只会替换表单模型中修改过的那些属性,因为你只想提供部分修改。setValue()中严格的检查可以帮你捕获复杂表单嵌套时可能出现的错误,而 patchValue() 将会默默地走向失败。

ProfileEditorComponent 中,如下 updateProfile 方法会为该用户修改名字和街道地址。

src/app/profile-editor/profile-editor.component.ts (patch value)

content_copyupdateProfile() {
  this.profileForm.patchValue({
    firstName: 'Nancy',
    address: {
      street: '123 Drew Street'
    }
  });
}

通过往模板中添加一个按钮来模拟一次更新操作,以修改用户档案。

src/app/profile-editor/profile-editor.component.html (update value)

content_copy<p>
  <button (click)="updateProfile()">Update Profile</button>
</p>

当点击按钮时,profileForm 模型中只有 firstNamestreet 被修改了。注意,street 是在 address 属性的对象中被修改的。这种结构是必须的,因为 patchValue() 方法要针对模型的结构进行更新。patchValue() 只会更新表单模型中所定义的那些属性。

使用 FormBuilder 来生成表单控件

当需要与多个表单打交道时,手动创建多个表单控件实例会非常繁琐。FormBuilder 服务提供了一些便捷方法来生成表单控件。FormBuilder 在幕后也使用同样的方式来创建和返回这些实例,只是用起来更简单。 下面的小节中会重构 ProfileEditor 组件,用 FormBuilder 来代替手工创建这些 FormControlFormGroup

步骤 1 - 导入 FormBuilder

要想使用 FormBuilder 服务,请从 @angular/forms 包中导入它的类。

src/app/profile-editor/profile-editor.component.ts (import)

content_copyimport { FormBuilder } from '@angular/forms';

步骤 2 - 注入 FormBuilder 服务

FormBuilder 是一个可注入的服务,它是由 ReactiveFormModule 提供的。只要把它添加到组件的构造函数中就可以注入这个依赖。

src/app/profile-editor/profile-editor.component.ts (constructor)

content_copyconstructor(private fb: FormBuilder) { }

步骤 3 - 生成表单控件

FormBuilder 服务有三个方法:control()group()array()。这些方法都是工厂方法,用于在组件类中分别生成 FormControlFormGroupFormArray

把生成 profileForm 的代码改为用 group 方法来创建这些控件。

src/app/profile-editor/profile-editor.component.ts (form builder)

content_copyimport { Component } from '@angular/core';import { FormBuilder } from '@angular/forms'; @Component({  selector: 'app-profile-editor',  templateUrl: './profile-editor.component.html',  styleUrls: ['./profile-editor.component.css']})export class ProfileEditorComponent {  profileForm = this.fb.group({    firstName: [''],    lastName: [''],    address: this.fb.group({      street: [''],      city: [''],      state: [''],      zip: ['']    }),  });   constructor(private fb: FormBuilder) { }}

在上面的例子中,你可以使用 group() 方法,用和前面一样的名字来定义这些属性。这里,每个控件名对应的值都是一个数组,这个数组中的第一项是其初始值。

注意:你可以只使用初始值来定义控件,但是如果你的控件还需要同步或异步验证器,那就在这个数组中的第二项和第三项提供同步和异步验证器。

这两种方式达成了相同的效果。

src/app/profile-editor/profile-editor.component.ts (instances)

src/app/profile-editor/profile-editor.component.ts (form builder)

content_copyprofileForm = new FormGroup({
  firstName: new FormControl(''),
  lastName: new FormControl(''),
  address: new FormGroup({
    street: new FormControl(''),
    city: new FormControl(''),
    state: new FormControl(''),
    zip: new FormControl('')
  })
});

简单表单验证

当通过表单接收用户输入时,表单验证是必要的。本节讲解了如何把单个验证器添加到表单控件中,以及如何显示表单的整体状态。表单验证的更多知识在表单验证一章中有详细的讲解。

步骤 1 - 导入验证器函数

响应式表单包含了一组开箱即用的常用验证器函数。这些函数接收一个控件,用以验证并根据验证结果返回一个错误对象或空值。

@angular/forms 包中导入 Validators 类。

src/app/profile-editor/profile-editor.component.ts (import)

content_copyimport { Validators } from '@angular/forms';

步骤 2 - 把字段设为必填(required)

最常见的校验项是把一个字段设为必填项。本节描述如何为 firstName 控件添加“必填项”验证器。

ProfileEditor 组件中,把静态方法 Validators.required 设置为 firstName 控件值数组中的第二项。

src/app/profile-editor/profile-editor.component.ts (required validator)

content_copyprofileForm = this.fb.group({
  firstName: ['', Validators.required],
  lastName: [''],
  address: this.fb.group({
    street: [''],
    city: [''],
    state: [''],
    zip: ['']
  }),
});

HTML5 有一组内置的属性,用来进行原生验证,包括 requiredminlengthmaxlength 等。虽然是可选的,不过你也可以在表单的输入元素上把它们添加为附加属性来使用它们。这里我们把 required 属性添加到 firstName 输入元素上。

src/app/profile-editor/profile-editor.component.html (required attribute)

content_copy<input type="text" formControlName="firstName" required>

注意:这些 HTML5 验证器属性可以和 Angular 响应式表单提供的内置验证器组合使用。组合使用这两种验证器实践,可以防止在模板检查完之后表达式再次被修改导致的错误。

显示表单状态

现在,你已经往表单控件上添加了一个必填字段,它的初始值是无效的(invalid)。这种无效状态冒泡到其父 FormGroup 中,也让这个 FormGroup 的状态变为无效的。你可以通过该 FormGroup 实例的 status属性来访问其当前状态。

使用插值表达式显示 profileForm 的当前状态。

src/app/profile-editor/profile-editor.component.html (display status)

content_copy<p>
  Form Status: {{ profileForm.status }}
</p>

响应式表单

提交按钮被禁用了,因为 firstName 控件的必填项规则导致了 profileForm 也是无效的。在你填写了 firstName 输入框之后,该表单就变成了有效的,并且提交按钮也启用了。

要了解表单验证的更多知识,参见表单验证一章。

使用表单数组管理动态控件

FormArrayFormGroup 之外的另一个选择,用于管理任意数量的匿名控件。像 FormGroup 实例一样,你也可以往 FormArray 中动态插入和移除控件,并且 FormArray 实例的值和验证状态也是根据它的子控件计算得来的。 不过,你不需要为每个控件定义一个名字作为 key,因此,如果你事先不知道子控件的数量,这就是一个很好的选择。下面的例子展示了如何在 ProfileEditor 中管理一组绰号(aliases)。

步骤 1 - 导入 FormArray

@angular/form 中导入 FormArray,以使用它的类型信息。FormBuilder 服务用于创建 FormArray 实例。

src/app/profile-editor/profile-editor.component.ts (import)

content_copyimport { FormArray } from '@angular/forms';

步骤 2 - 定义 FormArray

你可以通过把一组(从零项到多项)控件定义在一个数组中来初始化一个 FormArray。为 profileForm 添加一个 aliases 属性,把它定义为 FormArray 类型。

使用 FormBuilder.array() 方法来定义该数组,并用 FormBuilder.control() 方法来往该数组中添加一个初始控件。

src/app/profile-editor/profile-editor.component.ts (aliases form array)

content_copyprofileForm = this.fb.group({  firstName: ['', Validators.required],  lastName: [''],  address: this.fb.group({    street: [''],    city: [''],    state: [''],    zip: ['']  }),  aliases: this.fb.array([    this.fb.control('')  ])});

FormGroup 中的这个 aliases 控件现在管理着一个控件,将来还可以动态添加多个。

步骤 3 - 访问 FormArray 控件

因为 FormArray 表示的是数组中具有未知数量的控件,因此通过 getter 来访问控件比较便捷,也容易复用。使用 getter 语法来创建一个名为 aliases 的类属性,以便从父控件 FormGroup 中接收绰号的 FormArray控件。

src/app/profile-editor/profile-editor.component.ts (aliases getter)

content_copyget aliases() {
  return this.profileForm.get('aliases') as FormArray;
}

这个 getter 提供了对 aliases 这个 FormArray 的便捷访问,以代替对该实例反复进行 profileForm.get()

注意:因为返回的控件的类型是 AbstractControl,所以你要为该方法提供一个显式的类型声明来访问 FormArray 特有的语法。

定义一个方法来把一个绰号控件动态插入到绰号 FormArray 中。用 FormArray.push() 方法把该控件添加为数组中的新条目。

src/app/profile-editor/profile-editor.component.ts (add alias)

content_copyaddAlias() {
  this.aliases.push(this.fb.control(''));
}

在这个模板中,这些控件会被迭代,把每个控件都显示为一个独立的输入框。

步骤 4 - 在模板中显示表单数组

在模型中定义了 aliasesFormArray 之后,你必须把它加入到模板中供用户输入。和 FormGroupNameDirective 提供的 formGroupName 一样,FormArrayNameDirective 也使用 formArrayName 在这个 FormArray 和模板之间建立绑定。

formGroupName <div> 元素的结束标签下方,添加一段模板 HTML。

src/app/profile-editor/profile-editor.component.html (aliases form array template)

content_copy<div formArrayName="aliases">
  <h3>Aliases</h3> <button (click)="addAlias()">Add Alias</button>

  <div *ngFor="let address of aliases.controls; let i=index">
    <!-- The repeated alias template -->
    <label>
      Alias:
      <input type="text" [formControlName]="i">
    </label>
  </div>
</div>

*ngFor 指令对 aliases FormArray 提供的每个 FormControl 进行迭代。因为 FormArray 中的元素是匿名的,所以你要把索引号赋值给 i 变量,并且把它传给每个控件的 formControlName 输入属性。

响应式表单

每当新的 alias 加进来时,FormArray 就会基于这个索引号提供它的控件。这将允许你在每次计算根控件的状态和值时跟踪每个控件。

添加绰号

最初,表单只包含一个绰号字段,点击 Add Alias 按钮,就出现了另一个字段。您还可以验证由模板底部的“Form Value”显示出来的表单模型所报告的这个绰号数组。

注意:除了为每个绰号使用 FormControl 之外,你还可以改用 FormGroup 来组合上一些额外字段。对其中的每个条目定义控件的过程和前面没有区别。

附录

响应式表单 API

下面列出了用于创建和管理表单控件的基础类和服务。

说明

AbstractControl

所有三种表单控件类(FormControl、FormGroup 和 FormArray)的抽象基类。它提供了一些公共的行为和属性。

FormControl

管理单体表单控件的值和有效性状态。它对应于 HTML 的表单控件,比如 <input> 或 <select>。

FormGroup

管理一组 AbstractControl 实例的值和有效性状态。该组的属性中包括了它的子控件。组件中的顶级表单就是 FormGroup。

FormArray

管理一些 AbstractControl 实例数组的值和有效性状态。

FormBuilder

一个可注入的服务,提供一些用于提供创建控件实例的工厂方法。

当导入 ReactiveFormsModule 时,你也获得了一些指令的访问权,用来以声明的方式在模板中绑定表单的数据模型。

Directives

指令

说明

FormControlDirective

把一个独立的 FormControl 实例绑定到表单控件元素。

FormControlName

把一个现有 FormGroup 中的 FormControl 根据名字绑定到表单控件元素。

FormGroupDirective

把一个现有的 FormGroup 绑定到 DOM 元素。

FormGroupName

把一个内嵌的 FormGroup 绑定到一个 DOM 元素。

FormArrayName

把一个内嵌的 FormArray 绑定到一个 DOM 元素。

与模板驱动表单的对比

模板驱动表单一章中介绍的模板驱动表单是一种截然不同的方式。

  • 你把 HTML 表单控件(比如 <input><select>)放进组件模板中,并且使用 ngModel 等指令把它们绑定到组件中的数据模型的属性。
  • 你不能创建 Angular 表单控件对象,Angular 指令会根据你提供的数据绑定信息替你创建它们。
  • 你不能推拉数据值。Angular 会用 ngModel 替你处理它们。当用户进行修改时,Angular 会更新这个可变的数据模型

虽然这意味着组件中的代码更少,但是模板驱动表单是异步工作的,这可能在更高级的场景中让开发复杂化。

异步 vs. 同步

响应式表单是同步的,而模板驱动表单是异步的。

使用响应式表单,你会在代码中创建整个表单控件树。 你可以立即更新一个值或者深入到表单中的任意节点,因为所有的控件都始终是可用的。

模板驱动表单会委托指令来创建它们的表单控件。 为了消除“检查完后又变化了”的错误,这些指令需要消耗一个以上的变更检测周期来构建整个控件树。 这意味着在从组件类中操纵任何控件之前,你都必须先等待一个节拍。

比如,如果你用 @ViewChild(NgForm) 查询来注入表单控件,并在生命周期钩子 ngAfterViewInit中检查它,就会发现它没有子控件。 你必须使用 setTimeout 等待一个节拍才能从控件中提取值、测试有效性,或把它设置为新值。

模板驱动表单的异步性让单元测试也变得复杂化了。 你必须把测试代码包裹在 async()fakeAsync() 中来解决要查阅的值尚不存在的情况。 使用响应式表单,在所期望的时机一切都是可用的。

AngularJS

Angular 是一个开发平台。它能帮你更轻松的构建 Web 应用。Angular 集声明式模板、依赖注入、端到端工具和一些最佳实践于一身,为你解决开发方面的各种挑战。

AngularJS目录

1.快速上手 | quick start
2.语言服务
3.安全
4.环境准备与部署
5.Service Worker
6.保持最新
7.从 AngularJS 升级
8.服务端渲染
9.Visual Studio 2015 快速上手
10.风格指南
11.国际化
12.测试
13.路由与导航
14. 教程 | Tutorial
15.架构
16.组件与模板
17.表单
18.可观察对象与RxJS
19.引导启动
20.Angular 模块
21.依赖注入
22.HttpClient
23.词汇表
24.AngularJS 应用
25.AngularJS 模块
26.AngularJS 事件
27.AngularJS HTML DOM
28.AngularJS 过滤器
29.AngularJS 控制器
30.AngularJS 指令
31.AngularJS 表达式
32.AngularJS 简介
33.AngularJS 参考手册
34.AngularJS 实例
35.AngularJS 输入验证
36.AngularJS 表单
37.AngularJS SQL
38.AngularJS 表格
39.AngularJS Http
40.AngularJS 包含
41.AngularJS Bootstrap
42.AngularJS API
43.AngularJS ng-checked 指令
44.AngularJS ng-change 指令
45.AngularJS ng-blur 指令
46.AngularJS ng-bind-template 指令
47.AngularJS ng-bind-html 指令
48.AngularJS ng-bind 指令
49.AngularJS ng-app 指令
50.AngularJS Scope(作用域)
51.AngularJS ng-model 指令
52.AngularJS ng-dblclick 指令
53.AngularJS ng-cut 指令
54.AngularJS ng-csp 指令
55.AngularJS ng-copy 指令
56.AngularJS ng-controller 指令
57.AngularJS ng-cloak 指令
58.AngularJS ng-click 指令
59.AngularJS ng-class-odd 指令
60.AngularJS ng-class-even 指令
61.AngularJS ng-class 指令
62.AngularJS ng-keyup 指令
63.AngularJS ng-keypress 指令
64.AngularJS ng-keydown 指令
65.AngularJS ng-init 指令
66.AngularJS ng-include 指令
67.AngularJS ng-if 指令
68.AngularJS ng-href 指令
69.AngularJS ng-hide 指令
70.AngularJS ng-focus 指令
71.AngularJS ng-disabled 指令
72.AngularJS ng-non-bindable 指令
73.AngularJS ng-mouseup 指令
74.AngularJS ng-mouseover 指令
75.AngularJS ng-mousemove 指令
76.AngularJS ng-mouseleave 指令
77.AngularJS ng-mouseenter 指令
78.AngularJS ng-mousedown 指令
79.AngularJS ng-model-options 指令
80.AngularJS ng-model 指令
81.AngularJS ng-list 指令
82.AngularJS ng-style 指令
83.AngularJS ng-srcset 指令
84.AngularJS ng-src 指令
85.AngularJS ng-show 指令
86.AngularJS ng-selected 指令
87.AngularJS ng-repeat 指令
88.AngularJS ng-readonly 指令
89.AngularJS ng-paste 指令
90.AngularJS ng-options 指令
91.AngularJS ng-open 指令
92.AngularJS ng-value 指令
93.AngularJS ng-switch 指令
94.AngularJS ng-submit 指令
95.AngularJS 服务(Service)
96.AngularJS Select(选择框)
97.AngularJS 动画
98.AngularJS 依赖注入