Angular 4.x 中有两种表单:
Template-Driven Forms - 模板驱动式表单 (类似于 Angular 1.x 中的表单 ) Reactive Forms (Model-Driven Forms) - 响应式表单Template-Driven Forms (模板驱动表单) ,我们之前的文章已经介绍过了,了解详细信息,请查看 - Angular 4.x Template-Driven Forms 。
Contents
Form base and interface
Form base
<form novalidate> <label> <span>Full name</span> <input type="text" name="name" placeholder="Your full name"> </label> <div> <label> <span>Email address</span> <input type="email" name="email" placeholder="Your email address"> </label> <label> <span>Confirm address</span> <input type="email" name="confirm" placeholder="Confirm your email address"> </label> </div> <button type="submit">Sign up</button></form>
接下来我们要实现的功能如下:
绑定 name、email、confirm 输入框的值 为所有输入框添加表单验证功能 显示验证异常信息 表单验证失败时,不允许进行表单提交 表单提交功能User interface
// signup.interface.tsexport interface User { name: string; account: { email: string; confirm: string; }}
ngModule and reactive forms
在我们继续深入介绍 reactive forms 表单前,我们必须在 @NgModule 中导入 @angular/forms 库中的 ReactiveFormsModule:
import { ReactiveFormsModule } from '@angular/forms';@NgModule({ imports: [ ..., ReactiveFormsModule ], declarations: [...], bootstrap: [...]})export class AppModule {}
友情提示:若使用 reactive forms,则导入 ReactiveFormsModule;若使用 template-driven 表单,则导入 FormsModule。
Reactive approach
我们将基于上面的定义的基础表单,创建 SignupFormComponent :
signup-form.component.ts
import { Component } from '@angular/core';@Component({ selector: 'signup-form', template: ` <form novalidate>...</form> `})export class SignupFormComponent { constructor() {}}
这是一个基础的组件,在我们实现上述功能前,我们需要先介绍 FormControl、FormGroup、FormBuilder 的概念和使用。
FormControl and FormGroup
我们先来介绍一下 FormControl 和 FormGroup 的概念:
1、FormControl - 它是一个为单个表单控件提供支持的类,可用于跟踪控件的值和验证状态,此外还提供了一系列公共API。
使用示例:
ngOnInit() { this.myControl = new FormControl('Semlinker');}
新闻热点
疑难解答
图片精选