使用ng2-admin搭建成熟可靠的後臺系統 -- ng2-admin(四)

使用ng2-admin搭建成熟可靠的後臺系統 -- ng2-admin(四)

完善動態表單組件

  • 添加正則驗證
  • 添加錯誤提示

添加正則驗證

先來設置一些錯誤提示,以及添加正則驗證(上一章可能遺留了部分路徑錯誤,能夠自行調整)
user-add.service.tscss

import { Injectable } from "@angular/core";

import {
  QuestionBase,
  InputQuestion,
  SelectQuestion
} from "../../../../theme/components/dynamic-form-components/dynamic-form-base";

import { regExp } from './../../../api/universal/regExp';

@Injectable()
export class UserAddService {
  getQuestions() {
    let questions: QuestionBase<any>[] = [
      new InputQuestion({
        key: "firstName",
        label: "First name",
        value: "Bombasto",
        required: true,
        order: 1
      }),

      new InputQuestion({
        key: "emailAddress",
        label: "Email",
        type: "email",
        required: true,
        reg: regExp.email,
        prompt: "郵箱格式不正確",
        order: 2
      }),

      new SelectQuestion({
        key: "brave",
        label: "Bravery Rating",
        value: "",
        options: [
          { key: "請選擇", value: "" },
          { key: "Solid", value: "solid" },
          { key: "Great", value: "great" },
          { key: "Good", value: "good" },
          { key: "Unproven", value: "unproven" }
        ],
        required: true,
        order: 3
      })
    ];

    return questions.sort((a, b) => a.order - b.order);
  }
}

pages/api/universal/regExp.ts 這裏是提供的一些正則html

export const regExp = {
  number: /^\d{1,6}$/,

  tel: /^(\+86)?(\s)?(\d{1,4}-)?\d{5,11}$/,

  phone: /^1[34578]\d{9}$/,

  email: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/,

  text: /^[a-zA-Z\u4e00-\u9fa5]{2,9}/,

  name: /^[a-zA-Z\u4e00-\u9fa5]{2,9}/,

  file: /[2-9]{1,2}/,

  password: /^(?=.*?[A-Za-z]+)(?=.*?[0-9]+)(?=.*?[A-Za-z]).{6,16}$/,

  strongPassword: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{6,16}$/,  //要求大小寫字母數字特殊符號四選三

  approvalStatus: /(2|3)/,
};

添加錯誤提示

在驗證沒法經過時,用戶不清楚本身未經過驗證的選項,因此如今須要加入錯誤提示,友好的提示用戶。
  • 添加一些樣式

dynamic-form.component.ts 添加git

import "style-loader!./dynamic-fom-components.component.scss";

dynamic-fom-components.component.scssgithub

$errorColor: #fa758e;

.form-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  label {
    width: 10%;
    margin-right: 20px;
    i {
      color: $errorColor;
      margin-right: 5px;
    }
  }
  .form-control {
    width: 25%;
  }
  .prompt-error {
    color: $errorColor;
    margin-left: 20px;
  }
}
  • 添加默認的錯誤提示

question-base.tsapi

this.prompt = options.prompt || '該項爲必填/選項';
  • 添加錯誤提示

咱們使用的是響應式表單組成的動態表單,因此對應的 FormControl 應該有如下幾個屬性能夠幫助咱們添加提示app

  • valid 是否驗證經過
  • touched 是否操做過
  • value 控件的值

如今來爲控件添加提示樣式flex

先爲 QuestionControlService 添加一個公開的方法,用於設置 setterui

question-control.service.tsthis

...
export class QuestionControlService {
    ...
    public getControlProperty(): void {
      Object.defineProperty(this, 'isValid', {
        get() {
          return this.form.controls[this.question.key].valid;
        }
      });

      Object.defineProperty(this, 'isTouched', {
        get() {
          return this.form.controls[this.question.key].touched;
        }
      });
    }
}

這裏是將用戶表單中 FormControl 的 valid 和 touched 屬性設置爲 getter, 以便實時更新狀態。spa

如今來爲 InputTextboxComponent 注入這幾個 getter

input-textbox.component.ts

export class InputTextboxComponent {
  ...
  constructor(private qcs: QuestionControlService) {
    qcs.getControlProperty.call(this, null);
  }
}

而後須要在 html 中添加一些規則, 來顯示這些錯誤提示

input-textbox.component.html

<div class="form-container" [formGroup]="form" [ngClass]="{'has-error':!isValid && isTouched,
'has-success': isValid && isTouched}">
  <label for=""><i>*</i>{{question.label}}</label>
  <input class="form-control" [formControlName]="question.key" [id]="question.key" [type]="question.type">
  <span *ngIf="!isValid && !!isTouched" class="prompt-error">{{question.prompt}}</span>
</div>

這樣就大功告成,如下是實際效果圖

當驗證不經過時:
mark

錯誤提示出現,輸入框有紅色線框環繞,且提交按鈕爲置灰狀態

當驗證經過時:
mark

全部選項有正確提示,且表單可提交

讀者可自行完成 InputSelectComponent 的錯誤提示驗證

下章將會講解如何提交一個表單,基本的增刪改查,將會使用到 httpClient.

(此章以及此章前,代碼都提交在 ng2-admin 的 development 分支上,在將來會分開分支,方便讀者練習)

相關文章
相關標籤/搜索