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指令来控制显示无效反馈信息。如果输入项为空,则显示“该输入项为必填项”,否则显示“该输入项不符合规范”。

相关内容

热门资讯

必备科技!拱趴大菠萝有挂吗,德... 您好,拱趴大菠萝有挂吗这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在...
一分钟了解!德州私人局怎么透视... 一分钟了解!德州私人局怎么透视,pokemmo手机脚本,2025新版教程(有挂透视);原来确实真的有...
一分钟揭秘!哈糖大菠萝开挂,h... 一分钟揭秘!哈糖大菠萝开挂,hhpoker作弊码,必胜教程(有挂技巧);1.哈糖大菠萝开挂 ai辅助...
今日公布!哈糖大菠萝可以开挂吗... 今日公布!哈糖大菠萝可以开挂吗,wepoker怎么看底牌,详细教程(有挂方法)是由北京得哈糖大菠萝可...
玩家攻略!哈糖大菠萝有挂吗,佛... 玩家攻略!哈糖大菠萝有挂吗,佛手在线大菠萝智能辅助器,2025新版技巧(有挂软件);1分钟了解详细教...
最新技巧!模拟器打开hhpok... 最新技巧!模拟器打开hhpoker,wpk官网下载链接,我来教教你(有挂方法);模拟器打开hhpok...
一分钟揭秘!pokemmo脚本... 一分钟揭秘!pokemmo脚本,hhpoker脚本,微扑克教程(有挂技巧);建议优先通过pokemm...
安装程序教程!德普之星辅助器怎... 安装程序教程!德普之星辅助器怎么用,wepoker辅助器怎么弄,微扑克教程(有挂透明)1、不需要AI...
记者发布!wepoker黑侠辅... 1、记者发布!wepoker黑侠辅助器正版下载,wejoker黑侠辅助器,高科技教程(有挂教程)。2...
实测教程!wepoker插件辅... 实测教程!wepoker插件辅助,wepoker有辅助功能吗,软件教程(有挂攻略)关于wepoker...