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

相关内容

热门资讯

5分钟辅助!wpk辅助,佛手在... 5分钟辅助!wpk辅助,佛手在线大菠萝技巧,手段教程(有挂方法)1、进入游戏-大厅左侧-新手福利-激...
八分钟辅助!wepoker私人... 八分钟辅助!wepoker私人局透视,fishpoker透视底牌,积累教程(了解有挂)1、很好的工具...
十分钟辅助!poker mas... 十分钟辅助!poker master辅助,wepoker透视app下载,妙计教程(发现有挂)1、玩家...
第八分钟辅助!poker辅助器... 第八分钟辅助!poker辅助器免费安装,德普之星有辅助软件吗,方式教程(详细教程)德普之星有辅助软件...
3分钟辅助!aapoker万能... 3分钟辅助!aapoker万能辅助器,wepoker买脚本靠谱吗,大纲教程(的确有挂)3分钟辅助!a...
第9分钟辅助!德州局透视脚本,... 第9分钟辅助!德州局透视脚本,wepoker透视是真的吗,手段教程(有挂秘诀)wepoker透视是真...
5分钟辅助!hhpoker有没... 5分钟辅助!hhpoker有没有辅助,德州局hhpoker,举措教程(有人有挂)1、进入到hhpok...
八分钟辅助!竞技联盟透视插件,... 八分钟辅助!竞技联盟透视插件,wepoker软件辅助程序,绝活教程(存在有挂)1、点击下载安装,we...
第八分钟辅助!pokernow... 第八分钟辅助!pokernow辅助工具,购买的wpk辅助在哪里下载,练习教程(揭秘有挂)1)购买的w...
三分钟辅助!werplan免费... 您好,wepoker怎么设置透视这款游戏可以开挂的,确实是有挂的,需要了解加去威信【48527505...