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


一、Overview

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

對應官方文檔地址:

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

二、Contents

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

三、Knowledge Graph

思維導圖

四、Step by Step

4.1、表單簡介

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

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

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

4.2、模板驅動表單

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

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

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

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 完成組件與模板之間的數據雙向綁定

<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 屬性

4.2.2、跟蹤表單控件的狀態

在表單中使用 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 */
}

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

4.2.3、數據的有效性驗證

某些時候需要對於用戶輸入的信息做有效性驗證,此時可以在控件上添加上原生的 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 事件

4.3、響應式表單

4.3.1、快速上手

響應式表單依賴於 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);
  }
}

控件的數據操作

4.3.2、通過 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 更新控件數據

4.3.3、使用 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 {
  }
}
4.3.4、數據的有效性驗證

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

在響應式表單中,數據源來源於組件類,因此應該在組件類中直接把驗證器函數添加到對應的 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>

數據的有效性驗證

4.4、表單的自定義數據驗證

4.4.1、自定義驗證器

在很多的情況下,原生的驗證規則無法滿足我們的需要,此時需要創建自定義的驗證器來實現

對於響應式表單,我們可以定義一個方法,對控件的數據進行校驗,之后將方法作為參數添加到控件定義處即可

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>

模板驅動表單的數據驗證

4.4.2、跨字段的交叉驗證

有時候需要針對表單中的多個控件數據進行交叉驗證,此時就需要針對整個 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);
  }
}

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM