Angular动态验证,仅在表单控件无效时生效。
创始人
2024-10-24 15:00:59
0

可以使用Angular的内置验证器以及自定义验证器。当表单控件处于无效状态时,可以触发动态验证。下面是一个示例代码:


该输入项为必填项。
该输入项不符合规范。
import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html'
})
export class MyComponent implements OnInit {
  myFormControl: FormControl;

  ngOnInit() {
    this.myFormControl = new FormControl('', [
      Validators.required,
      this.customValidator // 自定义验证器
    ]);
  }

  customValidator(control: FormControl): {[key: string]: any} | null {
    const value = control.value;

    // 判断输入值是否符合规范
    if (value) {
      return null;
    }

    return { 'customValidator': { value } };
  }
}

上述代码中,myFormControl是一个表单控件,它具有内置的required验证器以及自定义的customValidator验证器。在HTML代码中,使用ngClass指令来动态绑定CSS类,当myFormControl处于无效状态并且用户已经访问过该控件时,添加is-invalid类。同时,使用*ngIf指令来控制显示无效反馈信息。如果输入项为空,则显示“该输入项为必填项”,否则显示“该输入项不符合规范”。

相关内容

热门资讯

一分钟大纲!wepoker私人... 一分钟大纲!wepoker私人局辅助(透视)总是存在有辅助工具(哔哩哔哩)1、金币登录送、破产送、升...
第八分钟窍要!德普之星有辅助软... 第八分钟窍要!德普之星有辅助软件吗(透视)切实有辅助透视(哔哩哔哩)该软件可以轻松地帮助玩家将德普之...
第4分钟手册!wepoker好... 第4分钟手册!wepoker好友房开挂(透视)竟然是有辅助安装(哔哩哔哩)wepoker好友房开挂能...
2分钟指南书!wepoker养... 2分钟指南书!wepoker养号规律(透视)真是有辅助透视(哔哩哔哩)wepoker养号规律辅助器是...
九分钟方针!wepoker俱乐... 九分钟方针!wepoker俱乐部辅助(透视)好像真的有辅助脚本(哔哩哔哩)1、起透看视 wepoke...
8分钟妙招!德州局脚本(透视)... 8分钟妙招!德州局脚本(透视)都是是真的有辅助安装(哔哩哔哩)德州局脚本辅助器是一种具有地方特色的麻...
两分钟大纲!hhpoker脚本... 两分钟大纲!hhpoker脚本下载(透视)一直真的是有辅助开挂(哔哩哔哩)1、hhpoker脚本下载...
第三分钟总结!wepoker透... 第三分钟总结!wepoker透视脚本免费下载pc(透视)竟然是有辅助安装(哔哩哔哩)1、wepoke...
8分钟操作!hhpoker怎么... 8分钟操作!hhpoker怎么防作必弊(透视)其实有辅助脚本(哔哩哔哩)1、全新机制【hhpoker...
八分钟指南书!wepoker安... 八分钟指南书!wepoker安装教程(透视)总是是真的有辅助透视(哔哩哔哩)一、wepoker安装教...