Angular 6: 带有条件自定义验证的嵌套表单
创始人
2024-10-16 05:00:24
0

在Angular 6中,可以使用自定义验证器来实现带有条件的嵌套表单验证。下面是一个示例代码,展示了如何创建一个带有条件自定义验证的嵌套表单。

首先,我们需要导入所需的模块和类:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';

然后,在组件类中定义一个带有嵌套表单的表单组:

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.myForm = this.fb.group({
      name: ['', Validators.required],
      age: ['', Validators.required],
      address: this.fb.group({
        street: ['', Validators.required],
        city: ['', Validators.required],
        state: ['', Validators.required]
      })
    });

    // 添加自定义验证器至表单控件
    const stateControl = this.myForm.get('address.state');
    stateControl.setValidators(this.customValidator.bind(this));
  }

  customValidator(control: FormControl) {
    const cityControl = this.myForm.get('address.city');
    const state = control.value;

    if (state === 'California' && !cityControl.value) {
      return { 'cityRequired': true };
    }

    return null;
  }

  onSubmit() {
    // 处理表单提交
  }
}

在上面的代码中,我们首先使用FormBuilder创建了一个myForm表单组,该组包含了一个嵌套表单address。然后,我们在address.state控件上添加了一个自定义验证器customValidator。该验证器会检查用户选择的州是否为“California”,如果是的话,那么就要求用户填写城市信息。

最后,在模板文件中,我们可以使用{{ myForm.valid }}来检查表单的有效性,并使用{{ myForm.errors | json }}来显示错误消息。

Name is required
Age is required
Street is required
City is required
City is required for California
State is required

在上面的模板代码中,我们使用了formGroup

相关内容

热门资讯

我来教教你!哈糖大菠萝万能挂,... 我来教教你!哈糖大菠萝万能挂,聚星ai辅助工具收费多少,实用技巧(有挂透明)关于聚星ai辅助工具收费...
玩家攻略推荐!wepoker有... 玩家攻略推荐!wepoker有辅助吗,德普之星透视辅助软件,2025版教程(有挂攻略);1.德普之星...
发现一款!werplan有挂吗... 发现一款!werplan有挂吗,wejoker私人辅助软件,必胜教程(有挂技巧);1.wejoker...
一分钟秒懂!wepoker安装... 一分钟秒懂!wepoker安装教程,来玩app 德州 辅助,教你攻略(有挂攻略)是由北京得来玩app...
玩家必看科普!智星德州可以透视... 玩家必看科普!智星德州可以透视吗,sohoo辅助,教你教程(有挂教程);人气非常高,ai更新快且高清...
玩家实测!wepoker轻量版... 玩家实测!wepoker轻量版有透视吗,来玩app破解版,wpk教程(有挂攻略);支持多人共享记分板...
分享个大家!wepoker有辅... 分享个大家!wepoker有辅助吗,德普辅助软件,安装教程(有挂方法);原来确实真的有挂(需添加指定...
一分钟秒懂!wepoker辅助... 一分钟秒懂!wepoker辅助器有哪些功能,wepoker免费脚本咨询,玩家教你(有挂攻略)准备好在...
玩家必看科普!wepoker轻... 玩家必看科普!wepoker轻量版透视方法,拱趴大菠萝自动计算机器人,新2025教程(有挂攻略)准备...
科普常识!佛手大菠萝有挂吗,w... 科普常识!佛手大菠萝有挂吗,wepoker辅助透视,分享教程(有挂透视);佛手大菠萝有挂吗软件透明挂...