Angular 4.x 中有兩種表單:
Template-Driven Forms - 模板驅動式表單 (類似于 Angular 1.x 中的表單 ) Reactive Forms - 響應式表單本文主要介紹 Template-Driven Forms (模板驅動式表單) ,將涉及 ngForm、ngModel、ngModelGroup、表單提交事件、表單驗證和異常信息輸出等內容。
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 template-driven forms
在我們繼續深入介紹 template-driven 表單前,我們必須在 @NgModule 中導入 @angular/forms 庫中的 FormModule:
import { FormsModule } from '@angular/forms';@NgModule({ imports: [ ..., FormsModule ], declarations: [...], bootstrap: [...]})export class AppModule {}友情提示:若使用 template-driven 表單,則導入 FormsModule;若使用 reactive forms,則導入 ReactiveFormsModule。
Template-driven approach
使用模板驅動的表單,我們基本上可以將組件類留空,直到我們需要讀取/寫入值 (例如提交和設置初始值)。我們將基于上面的定義的基礎表單,創建 SignupFormComponent :
signup-form.component.ts
import { Component } from '@angular/core';@Component({ selector: 'signup-form', template: ` <form novalidate>...</form> `})export class SignupFormComponent { constructor() {}}這是一個很基礎的組件,接下來我們導入之前定義的 User 接口,具體如下:
import { User } from './signup.interface';@Component({...})export class SignupFormComponent { public user: User = { name: '', account: { email: '', confirm: '' } };}初始化 SignupFormComponent 組件類中的用戶模型后,我們開始實現第一個功能點:即綁定 name、email、confirm 輸入框的值。
新聞熱點
疑難解答
圖片精選