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');}
新聞熱點
疑難解答
圖片精選