微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用ng2-admin搭建成熟可靠的后台系统 -- ng2-admin四

使用ng2-admin搭建成熟可靠的后台系统 -- ng2-admin(四)

完善动态表单组件

添加正则验证

先来设置一些错误提示,以及添加正则验证(上一章可能遗留了部分路径错误,可以自行调整)
user-add.service.ts

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",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" }
        ],order: 3
      })
    ];

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

pages/api/universal/regExp.ts 这里是提供的一些正则

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,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,//要求大小写字母数字特殊符号四选三

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

添加错误提示

在验证无法通过时,用户不清楚自己未通过验证的选项,所以现在需要加入错误提示,友好的提示用户

dynamic-form.component.ts 添加

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

dynamic-fom-components.component.scss

$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.ts

this.prompt = options.prompt || '该项为必填/选项';

我们使用的是响应式表单组成的动态表单,所以对应的 FormControl 应该有以下几个属性可以帮助我们添加提示

  • valid 是否验证通过
  • touched 是否操作过
  • value 控件的值

现在来为控件添加提示样式

先为 QuestionControlService 添加一个公开的方法,用于设置 setter

question-control.service.ts

...
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,以便实时更新状态。

现在来为 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>

这样就大功告成,以下是实际效果

当验证不通过时:

错误提示出现,输入框有红色线框环绕,且提交按钮为置灰状态

当验证通过时:

所有选项有正确提示,且表单可提交

读者可自行完成 InputSelectComponent错误提示验证

下章将会讲解如何提交一个表单,基本的增删改查,将会使用到 httpClient.

(此章以及此章前,代码都提交在 ng2-admin 的 development 分支上,在未来会分开分支,方便读者练习)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐