繁体   English   中英

Angular 2:从父组件验证子组件表单字段

[英]Angular 2 : Validate child component form fields from the parent component

问题陈述 :

父组件里面有<form>标签和一些<input>标签,子组件也有一些<input>标签,父组件有一个<submit> ,我们在提交表单时验证表单字段。

如何在submit表单时验证父组件中的子组件<input>字段?

要求:

如果父组件的表单包含其模板中包含input组件的子组件,则如果从父组件提交,则应在单击时验证这些input组件。

发现 :

SO中有很多帖子有相同的问题陈述,但没有找到任何合适的解决方案。以下所有帖子都验证了整个表格,但我的要求是验证子组件中的每个字段。

我们也可以使用template driven技术来实现它。 找到以下步骤

  • 从父组件到子组件,我们必须传递提交按钮事件。

     <button type="button" (click)="enterForm(parentForm)">Submit</button> 

    这里, parentForm是表单引用。

  • 使用来自父级的@ViewChild装饰器调用子组件方法,点击提交时传递submit button event

     @ViewChild('validateChildComponentForm') private ChildComponent: ChildComponent; 
  • 使用@ViewChild装饰器将子窗体的引用传递给子组件。

     @ViewChild('smartyStreetForm') form; enterForm(parentForm) { this.submitted = true; this.ChildComponent.validateChildForm(this.submitted); if(!parentForm.valid || !this.childFormValidCheck) { return; } else { // success code comes here. } } 
  • 现在在子组件方法中,我们将检查是否提交了父表单并且子组件表单有效,然后发出true,否则返回false到父组件中。 我们将使用@Output装饰器将isChildFormValid值发送到父组件中。

     @Output() isChildFormValid: EventEmitter<any> = new EventEmitter<any>(); public validateChildForm(data: any) { if (data === true) { if(this.form.valid === true) { this.isChildFormValid.emit(true); } else { this.isChildFormValid.emit(false); } } } 
  • 现在在父组件中,我们将获得isChildFormValid值。

     private isChildFormValid(formValid: any) { this.childFormValidCheck = formValid; } 

图示:

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM