這裏使用的是模型驅動的表單css
一、app.module.tshtml
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
...
imports: [ReactiveFormsModule, ...],
...
})
export class AppModule{
}
文件中加入了ReactiveFormsModule模塊,它是使用模型驅動表單所必須的。app
二、app.component.tsui
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { name: string score: number; formData: any; constructor() { } ngOnInit() { this.formData = new FormGroup({ name: new FormControl(this.name, Validators.compose([ Validators.required, ])), score: new FormControl(this.score, Validators.compose([ Validators.required, this.scoreValueValidator ])) }); } scoreValueValidator(control: FormControl): any { if (control.value < 0 || control.value > 100) { return { value: {info: '分數必須大於等於0,小於等於100'} }; } } onsubmit(data: any) { this.name= data.name; this.score = data.score } }
表單驗證,能夠使用內置的表單驗證,也能夠使用自定義驗證方法。this
(1) 內置表單驗證。spa
Validators是angular內置的驗證器模塊,能夠使用它實現強制字段、最小長度、最大長度和模式等,我這裏設置了name和score是強制字段,固然,你能夠加入Validators.minLength(6), Validators.maxLength(10),Validators.pattern("[^ @]*@[^ @]*")等等。code
(2) 自定義表單驗證。component
scoreValueValidator是自定義的驗證方法,用於驗證分數是否大於等於0,小於等於100,傳遞的參數是當前須要驗證的表單的FormControl,經過control.value能夠拿到輸入的分數值。orm
三、app.component.htmlhtm
<div class="container"> <form [formGroup] = "formData" (ngSubmit) = "onsubmit(formData.value)"> <div class="form-group"> <label for="name">姓名</label> <em>*</em> <input type="text" class="form-control" formControlName="name" id="name"> <div [hidden]="formData.get('name').valid || formData.get('name').untouched" class="small"> <p [hidden]="!formData.hasError('required', 'threshold')">必填項</p> </div> </div> <div class="form-group"> <label for="score">分數</label> <em>*</em> <input type="number" min="0" max="100" class="form-control" formControlName="score" id="score"> <div [hidden]="formData.get('score').valid || formData.get('score').untouched" class="small"> <p [hidden]="!formData.hasError('required', 'score')">必填項</p> <p [hidden]="!formData.hasError('value', 'score')">{{formData.getError('value', 'score')?.info}}</p> </div> <button type="submit" [disabled]="!formData.valid" class="btn btn-sm btn-primary">提交</button> </form> </div>
頁面中顯示錯誤信息
對於提交按鈕,咱們已經在方括號中添加了disabled,它被賦予值 !formData.valid。所以,若是formData.valid無效,按鈕將保持禁用狀態,用戶將沒法提交它。
四、app.component.css
em { color:red; margin-left: 0.25em } .ng-touched:not(form),.ng-invalid:not(form) { border: 1px solid #f00; } .ng-valid:not(form),.ng-untouched:not(form) { border: 1px solid #ddd; } p{ color:#f00; }