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方法中,遍历子表单的所有控件,并将其标记为'已触摸”并更新其值和有效性状态。

相关内容

热门资讯

透视透视!wepoker手机插... 透视透视!wepoker手机插件,wepoker辅助是真的吗,指引教程(原来真的是有挂)-哔哩哔哩1...
透视智能ai!we poker... 透视智能ai!we poker辅助器,wepoker怎么看底牌,举措教程(本来真的是有挂)-哔哩哔哩...
透视私人局!德州局透视脚本免费... 您好,德州局透视脚本免费版下载手机版这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704...
透视透视挂!wepoker辅助... 透视透视挂!wepoker辅助器是真的吗,哈糖大菠萝免费辅助器,资料教程(竟然是有挂)-哔哩哔哩1、...
透视新版!wepoker怎么买... 透视新版!wepoker怎么买辅助,wepoker分析,机巧教程(真是真的有挂)-哔哩哔哩1、进入游...
透视计算!拱趴大菠萝挂,aap... 透视计算!拱趴大菠萝挂,aapoker怎么设置提高好牌几率,步骤教程(本来存在有挂)-哔哩哔哩1、任...
透视挂!wejoker内置辅助... 透视挂!wejoker内置辅助(透视)开挂辅助技巧(本来真的是有挂)-哔哩哔哩1、wejoker内置...
透视插件!哈糖大菠萝挂法,we... 透视插件!哈糖大菠萝挂法,wepoker透视脚本免费app,演示教程(都是是有挂)-哔哩哔哩1)we...
透视存在!hhpoker真能买... 透视存在!hhpoker真能买到挂吗,扑克之星辅助,模板教程(都是真的有挂)-哔哩哔哩hhpoker...
透视自建房!hhpoker可以... 透视自建房!hhpoker可以控制吗(透视)开挂辅助app(其实是真的挂)-哔哩哔哩该软件可以轻松地...