angular使用from动态设置验证器(clearValidators、setValidators)

原文链接:https://www.longkui.site/program/frontend/angularfrom/4787/

0.背景

调试一个angular的form表单,根据条件动态赋予表单的权限验证。

主要介绍clearValidators和setValidators的用法。

1.代码

初始化代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { Component, OnInit,  } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
 
@Component({
  selector: 'list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.less']
})
export class ListComponent implements OnInit {
    form: FormGroup;
 
  constructor(
    private formFB: FormBuilder,
  ) { }
  
  ngOnInit() {
    //初始化form
    this.form = this.formFB.group({
      id: [null, [Validators.required]],  //id, 不能为空
      name: [null, [Validators.required]], // 姓名
      code: [null, [Validators.required]], // code
      num: [null, null], // num,可以为空
    })
  }
}

上面的代码用于初始化form表单。

然后,新增一个方法,用于动态配置验证器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { Component, OnInit,  } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
 
@Component({
  selector: 'list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.less']
})
export class ListComponent implements OnInit {
    formNew: FormGroup;
 
  constructor(
    private formFB: FormBuilder,
  ) { }
  
  ngOnInit() {
    //初始化form
    this.formNew = this.formFB.group({
      id: [null, [Validators.required]],  //id, 不能为空
      name: [null, [Validators.required]], // 姓名
      code: [null, [Validators.required]], // code
      num: [null, null], // num,可以为空
    })
  
  }
  flag=false
  check(){
    if(this.flag){
    this.formNew.get('name').setValidators([Validators.required]); //设置name字段为必须验证
 
    }else{
        this.formNew.get('name').clearValidators()  //清除name字段验证
    }
  
}

通过setValidators 和clearValidators 可以动态设置验证和清除验证。

 

posted on   longkui  阅读(316)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示