Angular 從入坑到挖坑 - 表單控件概覽

Overview

angular 入坑記錄的筆記第三篇,介紹 angular 中表單控件的相關概念,瞭解如何在 angular 中建立一個表單,以及如何針對表單控件進行數據校驗。css

對應官方文檔地址:html

配套代碼地址:angular-practice/src/forms-overviewreact

Contents

  1. Angular 從入坑到棄坑 - Angular 使用入門
  2. Angular 從入坑到挖坑 - 組件食用指南
  3. Angular 從入坑到挖坑 - 表單控件概覽

Knowledge Graph

思惟導圖

Step by Step

表單簡介

用來處理用戶的輸入,經過從視圖中捕獲用戶的輸入事件、驗證用戶輸入的是否知足條件,從而建立出表單模型修改組件中的數據模型,達到獲取用戶輸入數據的功能git

模板驅動表單 響應式表單
創建表單 由組件隱式的建立表單控件實例 在組件類中進行顯示的建立控件實例
表單驗證 指令 函數

在表單數據發生變動時,模板驅動表單經過修改 ngModel 綁定的數據模型來完成數據更新,而響應式表單在表單數據發生變動時,FormControl 實例會返回一個新的數據模型,而不是直接修改原來的數據模型程序員

模板驅動表單

經過使用表單的專屬指令(例如 ngModel 進行雙向數據綁定)將數據值和一些對於用戶的行爲約束(某個字段必須填啊、某個字段長度超過了長度限制啊)綁定到組件的模板中,從而完成與用戶的交互github

模板驅動表單的雙向數據綁定

在根模塊中引入 FormsModule,並添加到根模塊的 imports 數組中typescript

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

// 引入 FormsModule
import { FormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TemplateDrivenFormsComponent } from './template-driven-forms/template-driven-forms.component';

@NgModule({
  declarations: [
    AppComponent,
    ReactiveFormsComponent,
    DynamicFormsComponent,
    TemplateDrivenFormsComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule // 添加到應用模塊中
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
複製代碼

新建一個類文件,用來承載組件與模板之間進行雙向數據綁定的數據信息編程

ng g class classes/hero
複製代碼
export class Hero {

  /** * ctor * @param name 姓名 * @param age 年紀 * @param gender 性別 * @param location 住址 */
  constructor(public name: string, public age: number, public gender: string, public location: string) {
  }
}
複製代碼

在組件的模板中建立承載數據的表單信息,並使用 ngModel 完成組件與模板之間的數據雙向綁定json

<form>
  <div class="form-group">
    <label for="name">姓名:</label>
    <input type="text" name="name" id="name" [(ngModel)]="hero.name" class="form-control" autocomplete="off" required minlength="4">
  </div>
  <div class="form-group">
    <label for="age">年齡:</label>
    <input type="number" name="age" id="age" [(ngModel)]="hero.age" class="form-control" required>
  </div>
  <div class="form-group">
    <label for="gender">性別:</label>
    <div class="form-check" *ngFor="let gender of genders">
      <input class="form-check-input" type="radio" name="gender" id="{{gender.id}}" value="{{gender.value}}" [(ngModel)]="hero.gender">
      <label class="form-check-label" for="{{gender.id}}">
        {{gender.text}}
      </label>
    </div>
  </div>
  <div class="form-group">
    <label for="location">住址:</label>
    <select name="location" id="location" [(ngModel)]="hero.location" class="form-control" required>
      <option value="{{location}}" *ngFor="let location of locations">{{location}}</option>
    </select>
  </div>
  <button type="submit" (click)="submit()" class="btn btn-primary">Submit</button>
</form>

<p>
  表單的數據信息:{{hero | json}}
</p>
複製代碼
import { Component, OnInit } from '@angular/core';

import { Hero } from './../classes/hero';

@Component({
  selector: 'app-template-driven-forms',
  templateUrl: './template-driven-forms.component.html',
  styleUrls: ['./template-driven-forms.component.scss']
})
export class TemplateDrivenFormsComponent implements OnInit {
  constructor() { }

  // 性別選項
  public genders = [{
    id: 'male', text: '男', value: true
  }, {
    id: 'female', text: '女', value: false
  }];

  /** * 住址下拉 */
  public locations: Array<string> = ['beijing', 'shanghai', 'hangzhou', 'wuhan'];

  hero = new Hero('', 18, 'true', 'beijing');

  ngOnInit(): void {
  }

  submit() {

  }
}
複製代碼

雙向綁定

在使用 ngModel 進行模板綁定時,angular 在 form 標籤上自動附加了一個 NgForm 指令,由於 NgForm 指令會控制表單中帶有 ngModel 指令和 name 屬性的元素,而 name 屬性則是 angular 用來註冊控件的 key,因此在表單中使用 ngModel 進行雙向數據綁定時,必需要添加 name 屬性bootstrap

跟蹤表單控件的狀態

在表單中使用 ngModel 以後,NgModel 指令經過更新控件的 css 類,達到反映控件狀態的目的

狀態 發生時的 css 類 沒發生的 css 類
控件被訪問 ng-touched ng-untouched
控件的值發生變化 ng-dirty ng-pristine
控件的值是否有效 ng-valid ng-invalid

跟蹤表單控件的狀態

經過這些控件的 css 類樣式,就能夠經過添加自定義的 css 樣式在用戶輸入內容不知足條件時進行提示

.ng-valid[required], .ng-valid.required  {
  border-left: 5px solid #42A948; /* green */
}

.ng-invalid:not(form)  {
  border-left: 5px solid #a94442; /* red */
}
複製代碼

給予用戶輸入驗證的視覺反饋

數據的有效性驗證

某些時候須要對於用戶輸入的信息作有效性驗證,此時能夠在控件上添加上原生的 HTML 表單驗證器來設定驗證條件,當表單控件的數據發生變化時,angular 會經過指令的方式對數據進行驗證,從而生成錯誤信息列表

在進行用戶輸入數據有效性驗證時,在控件上經過添加一個模板引用變量來暴露出 ngModel,從而在模板中獲取到指定控件的狀態信息,以後就能夠經過獲取錯誤信息列表來進行反饋

<div class="form-group">
    <label for="name">姓名:</label>
    <!-- 將 ngModel 指令經過模板引用變量的形式暴露出來,從而獲取到控件的狀態 -->
    <input type="text" name="name" id="name" [(ngModel)]="hero.name" class="form-control" autocomplete="off" required minlength="4" #name="ngModel">
    <!-- 在用戶有改動數據 or 訪問控件以後纔對數據的有效性進行驗證 -->
    <div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
      <div *ngIf="name.errors.required">
        姓名不能爲空
      </div>
      <div *ngIf="name.errors.minlength">
        姓名信息不能少於 4 個字符長度
      </div>
    </div>
  </div>
複製代碼

數據驗證

在數據驗證失敗的狀況下,對於系統來講,表單是不容許提交的,所以能夠將提交事件綁定到表單的 ngSubmit 事件屬性上,經過模板引用變量的形式,在提交按鈕處進行數據有效性判斷,當無效時,禁用表單的提交按鈕

<form (ngSubmit)="submit()" #heroForm="ngForm">
  <div class="form-group">
    <label for="name">姓名:</label>
    <!-- 將 ngModel 指令經過模板引用變量的形式暴露出來,從而獲取到控件的狀態 -->
    <input type="text" name="name" id="name" [(ngModel)]="hero.name" class="form-control" autocomplete="off" required minlength="4" #name="ngModel">
    <!-- 在用戶有改動數據 or 訪問控件以後纔對數據的有效性進行驗證 -->
    <div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
      <div *ngIf="name.errors.required">
        姓名不能爲空
      </div>
      <div *ngIf="name.errors.minlength">
        姓名信息不能少於 4 個字符長度
      </div>
    </div>
  </div>
  <div class="form-group">
    <label for="age">年齡:</label>
    <input type="number" name="age" id="age" [(ngModel)]="hero.age" class="form-control" required>
  </div>
  <div class="form-group">
    <label for="gender">性別:</label>
    <div class="form-check" *ngFor="let gender of genders">
      <input class="form-check-input" type="radio" name="gender" id="{{gender.id}}" value="{{gender.value}}" [(ngModel)]="hero.gender">
      <label class="form-check-label" for="{{gender.id}}">
        {{gender.text}}
      </label>
    </div>
  </div>
  <div class="form-group">
    <label for="location">住址:</label>
    <select name="location" id="location" [(ngModel)]="hero.location" class="form-control" required>
      <option value="{{location}}" *ngFor="let location of locations">{{location}}</option>
    </select>
  </div>
  <button type="submit" [disabled]="!heroForm.form.valid" class="btn btn-primary">Submit</button>
</form>
複製代碼

綁定 ngSubmit 事件

響應式表單

快速上手

響應式表單依賴於 ReactiveFormsModule 模塊,所以在使用前須要在根模塊中引入

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

// 引入 ReactiveFormsModule
import { ReactiveFormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ReactiveFormsComponent } from './reactive-forms/reactive-forms.component';

@NgModule({
  declarations: [
    AppComponent,
    ReactiveFormsComponent,
    DynamicFormsComponent,
    TemplateDrivenFormsComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule // 添加到應用模塊中
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
複製代碼

在使用響應式表單時,一個 FormControl 類的實例對應於一個表單控件,在使用時,經過將控件的實例賦值給屬性,後續則能夠經過監聽這個自定義的屬性來跟蹤表單控件的值和狀態

import { Component, OnInit } from '@angular/core';

// 引入 FormControl 對象
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-reactive-forms',
  templateUrl: './reactive-forms.component.html',
  styleUrls: ['./reactive-forms.component.scss']
})
export class ReactiveFormsComponent implements OnInit {

  // 定義屬性用來承接 FormControl 實例
  public name = new FormControl('');

  constructor() { }

  ngOnInit(): void {
  }

}
複製代碼

當在組件中建立好控件實例後,經過給視圖模板上的表單控件添加 formControl 屬性綁定,從而將控件實例與模板中的表單控件關聯起來

<form>
  <div class="form-group">
    <label for="name">姓名:</label>
    <input type="text" id="name" [formControl]='name' class="form-control" autocomplete="off">
  </div>
</form>


<div>
  name 控件的數據值: {{ name | json }}
</div>
複製代碼

綁定表單屬性與表單控件

經過使用 FormControl 控件的 value 屬性,能夠得到當前表單控件的一份數據值拷貝,經過 setValue 方法則能夠更新表單的控件值

import { Component, OnInit } from '@angular/core';

// 引入 FormControl 對象
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-reactive-forms',
  templateUrl: './reactive-forms.component.html',
  styleUrls: ['./reactive-forms.component.scss']
})
export class ReactiveFormsComponent implements OnInit {

  // 定義屬性用來承接 FormControl 實例
  public name = new FormControl('12345');

  constructor() { }

  ngOnInit(): void {
  }

  getName() {
    alert(this.name.value);
  }

  setName() {
    this.name.setValue(1111111);
  }
}
複製代碼

控件的數據操做

經過 FomGroup 組合多個控件

一個表單不可能只有一個控件,經過在組件中構造 FormGroup 實例來完成對於多個表單控件的統一管理

在使用 FormGroup 時,一樣在組件中定義一個屬性用來承載控件組實例,而後將控件組中的每個控件做爲屬性值添加到實例中

import { Component, OnInit } from '@angular/core';

// 引入 FormControl 和 FormGroup 對象
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-reactive-forms',
  templateUrl: './reactive-forms.component.html',
  styleUrls: ['./reactive-forms.component.scss']
})
export class ReactiveFormsComponent implements OnInit {

  // 定義對象屬性來承接 FormGroup 實例
  public profileForm = new FormGroup({
    name: new FormControl('啦啦啦'),
    age: new FormControl(12)
  });

  constructor() { }

  ngOnInit(): void {
  }
}
複製代碼

在視圖模板中,將承接 FormGroup 實例的屬性經過 formGroup 指令綁定到 form 元素,而後將控件組的每個屬性經過 formControlName 綁定到具體對應的表單控件上

<form [formGroup]='profileForm'>
  <div class="form-group">
    <label for="name">姓名:</label>
    <input type="text" id="name" formControlName='name' class="form-control" autocomplete="off" required minlength="4">
  </div>
  <div class="form-group">
    <label for="age">年齡:</label>
    <input type="number" id="age" formControlName='age' class="form-control" autocomplete="off" required step="1" max="100" min="1">
  </div>
</form>

<div>
  FormGroup 表單組控件的值: {{ profileForm.value | json }}
</div>
複製代碼

經過 FormGroup 管理多個控件

當構建複雜表單時,能夠在 FormGroup 中經過嵌套 FormGroup 使表單的結構更合理

import { Component, OnInit } from '@angular/core';

// 引入 FormControl 和 FormGroup 對象
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-reactive-forms',
  templateUrl: './reactive-forms.component.html',
  styleUrls: ['./reactive-forms.component.scss']
})
export class ReactiveFormsComponent implements OnInit {

  // 定義對象屬性來承接 FormGroup 實例
  public profileForm = new FormGroup({
    name: new FormControl('啦啦啦'),
    age: new FormControl(12),
    address: new FormGroup({
      province: new FormControl('北京市'),
      city: new FormControl('北京'),
      district: new FormControl('朝陽區'),
      street: new FormControl('三里屯街道')
    })
  });

  constructor() { }

  ngOnInit(): void {
  }

  submit() {
    alert(JSON.stringify(this.profileForm.value));
  }
}
複製代碼

在視圖模板中,經過使用 formGroupName 屬性將 FormGroup 控件組中的 FormGroup 實例綁定到控件上

<form [formGroup]='profileForm' (ngSubmit)='submit()'>
  <div class="form-group">
    <label for="name">姓名:</label>
    <input type="text" id="name" formControlName='name' class="form-control" autocomplete="off" required minlength="4">
  </div>
  <div class="form-group">
    <label for="age">年齡:</label>
    <input type="number" id="age" formControlName='age' class="form-control" autocomplete="off" required step="1" max="100" min="1">
  </div>

  <div formGroupName='address'>
    <div class="form-group">
      <label for="province">省:</label>
      <input type="text" id="province" formControlName='province' class="form-control" autocomplete="off" required>
    </div>
    <div class="form-group">
      <label for="city">市:</label>
      <input type="text" id="city" formControlName='city' class="form-control" autocomplete="off" required>
    </div>
    <div class="form-group">
      <label for="district">區:</label>
      <input type="text" id="district" formControlName='district' class="form-control" autocomplete="off" required>
    </div>
    <div class="form-group">
      <label for="street">街道:</label>
      <input type="text" id="street" formControlName='street' class="form-control" autocomplete="off" required>
    </div>
  </div>

  <button type="submit" class="btn btn-primary" [disabled]="!profileForm.valid">數據提交</button>
</form>

<div>
  FormGroup 表單組控件的值: {{ profileForm.value | json }}
</div>
複製代碼

FormGroup 嵌套

對於使用了 FormGroup 的表單來講,當使用 setValue 進行數據更新時,必須保證新的數據結構與原來的結構相同,不然就會報錯

import { Component, OnInit } from '@angular/core';

// 引入 FormControl 和 FormGroup 對象
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-reactive-forms',
  templateUrl: './reactive-forms.component.html',
  styleUrls: ['./reactive-forms.component.scss']
})
export class ReactiveFormsComponent implements OnInit {

  // 定義對象屬性來承接 FormGroup 實例
  public profileForm = new FormGroup({
    name: new FormControl('啦啦啦'),
    age: new FormControl(12),
    address: new FormGroup({
      province: new FormControl('北京市'),
      city: new FormControl('北京'),
      district: new FormControl('朝陽區'),
      street: new FormControl('三里屯街道')
    })
  });

  constructor() { }

  ngOnInit(): void {
  }

  submit() {
    alert(JSON.stringify(this.profileForm.value));
  }

  updateProfile() {
    this.profileForm.setValue({
      name: '423'
    });
  }
}
複製代碼

FormGroup 使用 setValue 更新數據

某些狀況下,咱們只是想要更新控件組中的某個控件的數據值,這時須要使用 patchValue 的方式進行更新

import { Component, OnInit } from '@angular/core';

// 引入 FormControl 和 FormGroup 對象
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-reactive-forms',
  templateUrl: './reactive-forms.component.html',
  styleUrls: ['./reactive-forms.component.scss']
})
export class ReactiveFormsComponent implements OnInit {

  // 定義對象屬性來承接 FormGroup 實例
  public profileForm = new FormGroup({
    name: new FormControl('啦啦啦'),
    age: new FormControl(12),
    address: new FormGroup({
      province: new FormControl('北京市'),
      city: new FormControl('北京'),
      district: new FormControl('朝陽區'),
      street: new FormControl('三里屯街道')
    })
  });

  constructor() { }

  ngOnInit(): void {
  }

  submit() {
    alert(JSON.stringify(this.profileForm.value));
  }

  updateProfile() {
    this.profileForm.patchValue({
      name: '12345'
    });
  }
}
複製代碼

使用 patchValue 更新控件數據

使用 FormBuilder 生成表單控件

當控件過多時,經過 FormGroup or FormControl 手動的構建表單控件的方式會很麻煩,所以這裏能夠經過依賴注入 FormBuilder 類的方式來簡化的完成表單的構建

FormBuilder 服務有三個方法:control、group 和 array,用於在組件類中分別生成 FormControl、FormGroup 和 FormArray

使用 FormBuilder 構建的控件,每一個控件名對應的值都是一個數組,第一個值爲控件的默認值,第二項和第三項則是針對這個值設定的同步、異步驗證方法

import { Component, OnInit } from '@angular/core';

// 引入 FormBuilder 構建表單控件
import { FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-reactive-forms',
  templateUrl: './reactive-forms.component.html',
  styleUrls: ['./reactive-forms.component.scss']
})
export class ReactiveFormsComponent implements OnInit {

  /** * ctor * @param formBuilder 表單構造器 */
  constructor(private formBuilder: FormBuilder) { }

  public profileForm = this.formBuilder.group({
    name: ['啦啦啦'],
    age: [12],
    address: this.formBuilder.group({
      province: ['北京市'],
      city: ['北京'],
      district: ['朝陽區'],
      street: ['三里屯街道']
    })
  });

  ngOnInit(): void {
  }
}
複製代碼
數據的有效性驗證

同模板驅動表單的數據有效性驗證相同,在響應式表單中一樣能夠使用原生的表單驗證器,在設定規則時,須要將模板中控件名對應的數據值的第二個參數改成驗證的規則

在響應式表單中,數據源來源於組件類,所以應該在組件類中直接把驗證器函數添加到對應的 FormControl 的構造函數上。而後,一旦控件數據發生了變化,angular 就會調用這些函數

這裏建立針對指定控件的 getter 方法,從而在模板中經過此方法來獲取到指定控件的狀態信息

import { Component, OnInit } from '@angular/core';

// 引入 FormBuilder 構建表單控件
import { FormBuilder } from '@angular/forms';

// 引入 Validators 驗證器
import { Validators } from '@angular/forms';

@Component({
  selector: 'app-reactive-forms',
  templateUrl: './reactive-forms.component.html',
  styleUrls: ['./reactive-forms.component.scss']
})
export class ReactiveFormsComponent implements OnInit {

  /** * ctor * @param formBuilder 表單構造器 */
  constructor(private formBuilder: FormBuilder) { }

  public profileForm = this.formBuilder.group({
    name: ['', [
      Validators.required,
      Validators.minLength(4)
    ]],
    age: [12],
    address: this.formBuilder.group({
      province: ['北京市'],
      city: ['北京'],
      district: ['朝陽區'],
      street: ['三里屯街道']
    })
  });

  // 添加須要驗證控件 getter 方法,用來在模板中獲取狀態值
  get name() {
    return this.profileForm.get('name');
  }

  ngOnInit(): void {
  }
}
複製代碼
<form [formGroup]='profileForm' (ngSubmit)='submit()'>
  <div class="form-group">
    <label for="name">姓名:</label>
    <input type="text" id="name" formControlName='name' class="form-control" autocomplete="off" required minlength="4">

    <!-- 在用戶有改動數據 or 訪問控件以後纔對數據的有效性進行驗證 -->
    <div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
      <div *ngIf="name.errors.required">
        姓名不能爲空
      </div>
      <div *ngIf="name.errors.minlength">
        姓名信息不能少於 4 個字符長度
      </div>
    </div>
  </div>
  <div class="form-group">
    <label for="age">年齡:</label>
    <input type="number" id="age" formControlName='age' class="form-control" autocomplete="off" required step="1" max="100" min="1">
  </div>

  <div formGroupName='address'>
    <div class="form-group">
      <label for="province">省:</label>
      <input type="text" id="province" formControlName='province' class="form-control" autocomplete="off" required>
    </div>
    <div class="form-group">
      <label for="city">市:</label>
      <input type="text" id="city" formControlName='city' class="form-control" autocomplete="off" required>
    </div>
    <div class="form-group">
      <label for="district">區:</label>
      <input type="text" id="district" formControlName='district' class="form-control" autocomplete="off" required>
    </div>
    <div class="form-group">
      <label for="street">街道:</label>
      <input type="text" id="street" formControlName='street' class="form-control" autocomplete="off" required>
    </div>
  </div>

  <button type="button" class="btn btn-primary" (click)="updateProfile()">更新信息</button> &nbsp;
  <button type="submit" class="btn btn-primary" [disabled]="!profileForm.valid">數據提交</button>
</form>

<div>
  FormGroup 表單組控件的值: {{ profileForm.value | json }}
</div>
複製代碼

數據的有效性驗證

表單的自定義數據驗證

自定義驗證器

在不少的狀況下,原生的驗證規則沒法知足咱們的須要,此時須要建立自定義的驗證器來實現

對於響應式表單,咱們能夠定義一個方法,對控件的數據進行校驗,以後將方法做爲參數添加到控件定義處便可

import { Component, OnInit } from '@angular/core';

// 引入 FormBuilder 構建表單控件
import { FormBuilder } from '@angular/forms';

// 引入 Validators 驗證器
import { Validators } from '@angular/forms';

/** * 自定義驗證方法 * @param name 控件信息 */
function validatorName(name: FormControl) {
  return name.value === 'lala' ? { nameinvalid: true } : null;
}

@Component({
  selector: 'app-reactive-forms',
  templateUrl: './reactive-forms.component.html',
  styleUrls: ['./reactive-forms.component.scss']
})
export class ReactiveFormsComponent implements OnInit {

  /** * ctor * @param formBuilder 表單構造器 */
  constructor(private formBuilder: FormBuilder) { }

  public profileForm = this.formBuilder.group({
    name: ['', [
      Validators.required,
      Validators.minLength(4),
      validatorName // 添加自定義驗證方法
    ]],
    age: [12],
    address: this.formBuilder.group({
      province: ['北京市'],
      city: ['北京'],
      district: ['朝陽區'],
      street: ['三里屯街道']
    })
  });

  // 添加須要驗證控件 getter 方法,用來在模板中獲取狀態值
  get name() {
    return this.profileForm.get('name');
  }

  ngOnInit(): void {
  }
}
複製代碼

在驗證方法中,當數據有效時,返回 null,當數據無效時,則會返回一個對象信息,這裏的 nameinvalid 就是咱們在模板中獲取到的錯誤信息的 key 值

<div class="form-group">
    <label for="name">姓名:</label>
    <input type="text" id="name" formControlName='name' class="form-control" autocomplete="off" required minlength="4">

    <!-- 在用戶有改動數據 or 訪問控件以後纔對數據的有效性進行驗證 -->
    <div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
      <div *ngIf="name.errors.required">
        姓名不能爲空
      </div>
      <div *ngIf="name.errors.minlength">
        姓名信息不能少於 4 個字符長度
      </div>
      <div *ngIf="name.errors.nameinvalid">
        姓名無效
      </div>
    </div>
</div>
複製代碼

響應式表單控件的自定義數據驗證

在模板驅動表單中,由於不是直接使用的 FormControl 實例,所以這裏應該在模板上添加一個自定義的指令來完成對於控件數據的校驗

使用 angular cli 建立一個用來進行表單驗證的指令

ng g directive direactives/hero-validate
複製代碼

在建立完成指令以後,咱們須要將這個指令將該驗證器添加到已經存在的驗證器集合中,同時爲了使這個指令能夠與 angular 表單集成在一塊兒,咱們須要繼承 Validator 接口

import { Directive, Input } from '@angular/core';
import { AbstractControl, Validator, ValidationErrors, NG_VALIDATORS } from '@angular/forms';

@Directive({
  selector: '[appHeroValidate]',
  // 將指令註冊到 NG_VALIDATORS 使用 multi: true 將該驗證器添加到現存的驗證器集合中
  providers: [{ provide: NG_VALIDATORS, useExisting: HeroValidateDirective, multi: true }]
})
export class HeroValidateDirective implements Validator {

  constructor() { }

  /** * 對指定的控件執行同步驗證方法 * @param control 控件 */
  validate(control: AbstractControl): ValidationErrors | null {
    return control.value === 'lala' ? { 'nameInvalid': true } : null;
  }
}
複製代碼

當實現了繼承的 validate 方法後,就能夠在模板的控件上添加該指令

<div class="form-group">
    <label for="name">姓名:</label>
    <!-- 將 ngModel 指令經過模板引用變量的形式暴露出來,從而獲取到控件的狀態 -->
    <input type="text" name="name" id="name" [(ngModel)]="hero.name" class="form-control" autocomplete="off" required minlength="4" #name="ngModel" appHeroValidate>
    <!-- 在用戶有改動數據 or 訪問控件以後纔對數據的有效性進行驗證 -->
    <div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
      <div *ngIf="name.errors.required">
        姓名不能爲空
      </div>
      <div *ngIf="name.errors.minlength">
        姓名信息不能少於 4 個字符長度
      </div>
      <div *ngIf="name.errors.nameInvalid">
        姓名無效
      </div>
    </div>
</div>
複製代碼

模板驅動表單的數據驗證

跨字段的交叉驗證

有時候須要針對表單中的多個控件數據進行交叉驗證,此時就須要針對整個 FormGroup 進行驗證。所以這裏的驗證方法須要在定義控件組時做爲 FormGroup 的參數傳入

與單個字段的驗證方式類似,經過實現 ValidatorFn 接口,當表單數據有效時,它返回一個 null,不然返回 ValidationErrors 對象

import { Component, OnInit } from '@angular/core';

// 引入 FormControl 和 FormGroup 對象
import { FormControl, FormGroup, ValidatorFn, ValidationErrors } from '@angular/forms';

// 引入 FormBuilder 構建表單控件
import { FormBuilder } from '@angular/forms';

// 引入 Validators 驗證器
import { Validators } from '@angular/forms';

/** * 跨字段驗證 * @param controlGroup 控件組 */
const nameAgeCrossValidator: ValidatorFn = (controlGroup: FormGroup): ValidationErrors | null => {

  // 獲取子控件的信息
  //
  const name = controlGroup.get('name');
  const age = controlGroup.get('age');

  return name && age && name.value === 'lala' && age.value === 12 ? { 'nameAgeInvalid': true } : null;
};

@Component({
  selector: 'app-reactive-forms',
  templateUrl: './reactive-forms.component.html',
  styleUrls: ['./reactive-forms.component.scss']
})
export class ReactiveFormsComponent implements OnInit {
  /** * ctor * @param formBuilder 表單構造器 */
  constructor(private formBuilder: FormBuilder) { }

  public profileForm = this.formBuilder.group({
    name: ['', [
      Validators.required,
      Validators.minLength(4),
      validatorName
    ]],
    age: [12],
    address: this.formBuilder.group({
      province: ['北京市'],
      city: ['北京'],
      district: ['朝陽區'],
      street: ['三里屯街道']
    })
  }, { validators: [nameAgeCrossValidator] }); // 添加針對控件組的驗證器
  
  ngOnInit(): void {
  }
}
複製代碼

在針對多個字段進行交叉驗證時,在模板頁面中,則須要經過獲取整個表單的錯誤對象信息來獲取到交叉驗證的錯誤信息

<div class="form-group">
    <label for="name">姓名:</label>
    <input type="text" id="name" formControlName='name' class="form-control" autocomplete="off" required minlength="4">

    <!-- 在用戶有改動數據 or 訪問控件以後纔對數據的有效性進行驗證 -->
    <div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
      <div *ngIf="name.errors.required">
        姓名不能爲空
      </div>
      <div *ngIf="name.errors.minlength">
        姓名信息不能少於 4 個字符長度
      </div>
      <div *ngIf="name.errors.nameinvalid">
        姓名無效
      </div>
    </div>
  </div>
  <div class="form-group">
    <label for="age">年齡:</label>
    <input type="number" id="age" formControlName='age' class="form-control" autocomplete="off" required step="1" max="100" min="1">
    <div *ngIf="profileForm.errors?.nameAgeInvalid && (profileForm.touched || profileForm.dirty)" class="alert alert-danger">
      lala 不能是 12 歲
    </div>
</div>
複製代碼

響應式表單的跨字段交叉驗證

對於模板驅動表單,一樣是採用自定義指令的方式進行跨字段的交叉驗證,與單個控件的驗證不一樣,此時須要將指令添加到 form 標籤上,而後使用模板引用變量來獲取錯誤信息

import { Directive } from '@angular/core';
import { Validator, AbstractControl, ValidationErrors, ValidatorFn, FormGroup, NG_VALIDATORS } from '@angular/forms';

/** * 跨字段驗證 * @param controlGroup 控件組 */
const nameAgeCrossValidator: ValidatorFn = (controlGroup: FormGroup): ValidationErrors | null => {

  // 獲取子控件的信息
  //
  const name = controlGroup.get('name');
  const age = controlGroup.get('age');

  return name && age && name.value === 'lala' && age.value === 12 ? { 'nameAgeInvalid': true } : null;
};

@Directive({
  selector: '[appCrossFieldValidate]',
  providers: [{ provide: NG_VALIDATORS, useExisting: CrossFieldValidateDirective, multi: true }]
})
export class CrossFieldValidateDirective implements Validator {

  constructor() { }

  validate(control: AbstractControl): ValidationErrors | null {
    return nameAgeCrossValidator(control);
  }
}
複製代碼

模板驅動表單的跨字段交叉驗證

佔坑

        做者:墨墨墨墨小宇
        我的簡介:96年生人,出生於安徽某四線城市,畢業於Top 10000000 院校。.NET程序員,槍手死忠,喵星人。於2016年12月開始.NET程序員生涯,微軟.NET技術的堅決堅持者,立志成爲雲養貓的少年中面向谷歌編程最厲害的.NET程序員。
        我的博客:yuiter.com
        博客園博客:www.cnblogs.com/danvic712

相關文章
相關標籤/搜索