Angular-function 表单控制


模板功能

  1. 表单校验及错误信息展示
  2. 表单按钮禁用

模板代码:

import { FormGroup } from "@angular/forms";

export abstract class FormController {
  abstract Disabled: boolean;
  abstract form: FormGroup;
  abstract formErrors: { [key: string]: string };
  abstract validationMessages: { [key: string]: { [key: string]: string } };

  init(): void {
    this.Disabled = !this.validateForm();
    this.form.valueChanges.subscribe(() => {
      this.Disabled = !this.validateForm();
    });
  }

  validateForm(): boolean {
    let result = true;
    if (!this.form) return false;

    for (const field in this.formErrors) {
      if (this.formErrors.hasOwnProperty(field)) {
        this.formErrors[field] = '';
        const control = this.form.get(field);

        if (control && !control.valid) {
          const messages = this.validationMessages[field];

          for (const key in control.errors) {
            if (control.errors.hasOwnProperty(key)) {
              this.formErrors[field] += messages[key] + ' ';
              result = false;
            }
          }
        }
      }
    }
    return result;
  }
}

Demo

ts

引入FormController类即可

import {Component, OnInit} from '@angular/core';
import {FormController} from '../functions/form/formValied';
import {FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators} from "@angular/forms";
import {NgIf} from "@angular/common";

@Component({
  selector: 'app-test',
  standalone: true,
  imports: [
    FormsModule,
    NgIf,
    ReactiveFormsModule,
  ],
  templateUrl: './test.component.html',
  styleUrl: './test.component.css'
})
export class TestComponent extends FormController implements OnInit {
// 继承这些属性
  Disabled: boolean = true;
  form: FormGroup;
  formErrors = {
    token: "",
    password: "",
    password_confirmation: ""
  };
  validationMessages: {
    [key: string]: {
      [key: string]: string;
    };
  } = {
    "token": {
      'required': $localize`:token|重置密码页token:请输入您的token。`,
    },
    "password": {
      'required': $localize`:password|重置密码页密码:请输入您的密码。`,
      'minlength': $localize`:password|重置密码页密码:密码长度不能少于6个字符。`,
      'maxlength': $localize`:password|重置密码页密码:密码长度不能超过20个字符。`,
    },
    "password_confirmation": {
      'required': $localize`:repassword|重置密码页确认密码:请再次输入您的密码。`,
      'confirm': $localize`:repassword|重置密码页确认密码:两次输入的密码不一致。`,
    },
  };

  constructor() {
    super();
    //在这里定义自己的表单
    this.form = new FormGroup({
      token: new FormControl('', [Validators.required]),
      password: new FormControl('', [Validators.required, Validators.minLength(6), Validators.maxLength(20)]),
      password_confirmation: new FormControl('', [Validators.required, this.confirmationValidator])
    });
  }

  // 可以定义自己的校验逻辑
  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return {required: true};
    } else if (control.value !== this.form.get('password')!.value) {
      return {confirm: true};
    }
    return {};
  }

  ngOnInit() {
    //在此处插入初始化函数
    this.init()

  }
  submit(){

  }
}

html

使用的时候修改下面的控件部分即可

<div class="h-screen w-screen">
  <div class="max-w-lg mx-auto my-10 bg-white p-8 rounded-xl shadow shadow-slate-300">

    <div>
      <h1 class="text-4xl font-medium items-center">
        重置密码
      </h1>
      <p class="text-slate-500">
        请输入 token 和新密码
      </p>
<!--      此处是需要填写控件的部分-->
      <form
        [formGroup]="form"
        (ngSubmit)="submit()"
        class="my-10">
        <div class="flex flex-col space-y-5">
          <label>
            <!--      此处是需要填写控件的部分-->

            <input formControlName="token"
                   type="text"
                   class="w-full py-3 border border-slate-200 rounded-lg px-3 focus:outline-none focus:border-slate-500 hover:shadow"
                   i18n-placeholder="@@token"
                   placeholder="密钥">
            <!--      此处是需要填写控件的部分-->

            <div *ngIf="formErrors['token']" class="text-red-500 text-sm text-right">
              {{ formErrors["token"] }}
            </div>
          </label>
          <label>
            <!--      此处是需要填写控件的部分-->

            <input formControlName="password"
                   type="password"
                   class="w-full py-3 border border-slate-200 rounded-lg px-3 focus:outline-none focus:border-slate-500 hover:shadow"
                   i18n-placeholder="@@password"
                   placeholder="新密码">
            <!--      此处是需要填写控件的部分-->

            <div *ngIf="formErrors['password']" class="text-red-500 text-sm text-right">
              {{ formErrors["password"] }}
            </div>
          </label>
          <label>
            <!--      此处是需要填写控件的部分-->

            <input formControlName="password_confirmation"
                   type="password"
                   class="w-full py-3 border border-slate-200 rounded-lg px-3 focus:outline-none focus:border-slate-500 hover:shadow"
                   i18n-placeholder="@@password_confirmation"
                   placeholder="确认密码">
            <!--      此处是需要填写控件的部分-->

            <div *ngIf="formErrors['password_confirmation']" class="text-red-500 text-sm text-right">
              {{ formErrors["password_confirmation"] }}
            </div>
          </label>

          <!--      此处是需要填写控件的部分-->

          <button
            [disabled]="Disabled"
            class="w-full py-3 font-medium text-white bg-indigo-600 hover:bg-indigo-500 rounded-lg border-indigo-500 hover:shadow inline-flex space-x-2 items-center justify-center">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
                 stroke="currentColor"
                 class="w-6 h-6">
              <path stroke-linecap="round" stroke-linejoin="round"
                    d="M15.75 5.25a3 3 0 013 3m3 0a6 6 0 01-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 1121.75 8.25z"/>
            </svg>
            <span i18n="@@reset">
          重置密码
        </span>
          </button>
        </div>
      </form>

    </div>
  </div>
</div>

实际效果


如果本文帮助到了你,帮我点个广告可以咩(o′┏▽┓`o)


评论
  目录