Angular响应式表单在子组件上提交时无法触发验证。
创始人
2024-10-30 08:00:30
0

在子组件上手动触发验证,可以通过使用@ViewChild装饰器获取每个子组件的表单控件,并在提交钩子中手动调用其验证方法。以下是示例代码:

父组件模板:

父组件代码:

export class ParentComponent implements OnInit {
  parentForm: FormGroup;
  @ViewChild(ChildComponent) childComponent: ChildComponent;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.parentForm = this.fb.group({
      child: ['', Validators.required]
    });
  }

  onSubmit() {
    if (this.parentForm.valid && this.childComponent.childForm.valid) {
      console.log('Form submitted successfully');
    } else {
      console.log('Form submission failed');
    }
  }
}

子组件模板:

子组件代码:

export class ChildComponent {
  childForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.childForm = this.fb.group({
      name: ['', Validators.required]
    });
  }

  validate() {
    Object.values(this.childForm.controls).forEach(control => {
      control.markAsTouched();
      control.updateValueAndValidity();
    });
  }
}

在父组件中,使用@ViewChild来获取ChildComponent实例并存储在childComponent属性中。在提交钩子中,首先检查父表单是否有效,然后检查子组件的表单是否有效。如果子组件表单无效,则手动调用其validate方法以触发验证。在validate方法中,遍历子表单的所有控件,并将其标记为'已触摸”并更新其值和有效性状态。

相关内容

热门资讯

透视app!wepoker透视... 透视app!wepoker透视脚本(透视)原来是真的有挂(详细辅助2025新版);亲,关键说明,we...
教学盘点!约局吧怎么看有没有挂... 1、教学盘点!约局吧怎么看有没有挂,wepoker能不能透视,必赢方法(有挂软件)(UU poker...
透视智能ai!来玩app 德州... 透视智能ai!来玩app 德州 辅助(透视)一贯真的有挂(详细辅助透明挂教程);1、机器人多个强度级...
一分钟揭秘!hhpoker到底... 1、一分钟揭秘!hhpoker到底可以作弊吗,impoker辅助,规律教程(有挂技巧)。2、hhpo...
透视规律!aapoker真的假... 透视规律!aapoker真的假的(透视)竟然真的是有挂(详细辅助我来教教你)暗藏猫腻,小编详细说明原...
玩家必看教程!xpoker透视... 玩家必看教程!xpoker透视辅助,wepoker软件安装包,曝光教程(有挂技巧);最新版2024是...
透视科技!aapoker怎么设... 透视科技!aapoker怎么设置提高好牌几率(透视)都是存在有挂(详细辅助力荐教程)运辅助工具,进入...
免费测试版!hhpoker有没... 免费测试版!hhpoker有没有辅助,hhpoker德州透视挂,可靠技巧(有挂辅助);科技安装教程;...
透视玄学!wepoker透视辅... 透视玄学!wepoker透视辅助下载(透视)竟然是真的有挂(详细辅助科技教程)1、游戏颠覆性的策略玩...
安装程序教程!hhpoker必... 1、安装程序教程!hhpoker必备开挂,wepoker有透视吗,2025新版总结(有挂软件);详细...