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

相关内容

热门资讯

透视挂透视!werplan免费... 透视挂透视!werplan免费挂下载,wepoker的辅助器,资料教程(有挂分享)-哔哩哔哩该软件可...
透视了解!德普之星透视,hhp... 透视了解!德普之星透视,hhpoker辅助挂是真的吗,方针教程(有挂辅助)-哔哩哔哩1、进入游戏-大...
透视存在!德普之星透视辅助软件... 透视存在!德普之星透视辅助软件激活码,wepokerplus万能挂,课程教程(确实有挂)-哔哩哔哩1...
透视智能ai!wepoker智... 您好,wepoker智能辅助插件这款游戏可以开挂的,确实是有挂的,需要了解加去威信【48527505...
透视教学!wepoker俱乐部... 透视教学!wepoker俱乐部辅助,德州透视脚本,策略教程(真的有挂)-哔哩哔哩1、wepoker俱...
透视脚本!we-poker靠谱... 透视脚本!we-poker靠谱吗,wpk显示有辅助,教程书教程(有挂辅助)-哔哩哔哩1、游戏颠覆性的...
透视辅助!wpk透视怎么安装,... 透视辅助!wpk透视怎么安装,拱趴大菠萝万能挂,手段教程(有挂秘诀)-哔哩哔哩1、进入游戏-大厅左侧...
透视教学!wpk辅助最怕三个东... 透视教学!wpk辅助最怕三个东西,aapoker ai插件,课程教程(有挂分析)-哔哩哔哩1、下载好...
透视科技!wepoker怎么发... 透视科技!wepoker怎么发冤家牌,wepoker是不是有人用挂,练习教程(新版有挂)-哔哩哔哩1...
透视线上!哈糖大菠萝怎么挂,h... 透视线上!哈糖大菠萝怎么挂,hhpoker德州有挂吗,操作教程(有挂方式)-哔哩哔哩1、哈糖大菠萝怎...