對前端開發人員來講,表單是很是重要的,它負責用戶與程序的交互。它承載着一部分數據校驗的功能,以此減小服務端的壓力。本文就angular表單驗證的兩種方式進行闡述,若有問題,歡迎指正。css
文章目錄html
爲了向模板驅動表單中添加驗證,須要添加一些驗證屬性,這裏就用戶登陸界面爲例進行說明前端
一:新建項目
到工做路徑下,運行ng new valicate
建立一個angular項目,而後用vscode打開bootstrap
二:修改app.component.html模板文件
建立一個表單,有兩個輸入框,分別爲用戶名和密碼,接下來對這兩個輸入框進行驗證數組
app.component.htmlapp
<br><br> <div class="container-fluid"> <div class="row"> <div class="col-md-4"> </div> <div class="col-md-4"> <h1 class="form-group">Login</h1> <form role="form"> <div class="form-group"> <label for="exampleInputEmail1"> Email address </label> <input type="email" class="form-control" id="exampleInputEmail1" /> </div> <div class="form-group"> <label for="exampleInputPassword1"> Password </label> <input type="password" class="form-control" id="exampleInputPassword1" /> </div> <button type="submit" class="btn btn-primary"> Submit </button> </form> </div> <div class="col-md-4"> </div> </div> </div>
代碼中運用到的樣式均爲Bootstrap4中提供的css樣式,讀者能夠到其官網下載。
最終的樣式以下:ide
三:添加校驗
首先在app.module.ts
中,添加FormsModule
模塊,並增長到imports數組中ui
app.module.tsspa
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { FormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
而後在模板頁面中添加校驗器code
添加校驗的app.component.html
<br><br> <div class="container-fluid"> <div class="row"> <div class="col-md-4"> </div> <div class="col-md-4"> <h1 class="form-group">Login</h1> <form role="form"> <div class="form-group"> <label for="exampleInputEmail1"> Email address </label> <input type="email" class="form-control" id="exampleInputEmail1" [(ngModel)]="email" name="email" #emailFC="ngModel" required/> </div> <div *ngIf="emailFC.invalid" class="alert alert-danger"> 請輸入郵箱地址! </div> <div class="form-group"> <label for="exampleInputPassword1"> Password </label> <input type="password" class="form-control" id="exampleInputPassword1" /> </div> <button type="submit" class="btn btn-primary"> Submit </button> </form> </div> <div class="col-md-4"> </div> </div> </div>
最終效果以下:
四:注意事項
在Input標籤中必須添加name屬性,且 #name 與ts中class的屬性名稱不能相同,如圖
一:在app.module.ts中引用ReactiveFormsModule
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { StudentComponent } from './student/student.component'; @NgModule({ declarations: [ AppComponent, StudentComponent ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule ], providers: [], bootstrap: [ AppComponent ] }) export class AppModule { }
未完,等待更新