草庐IT

javascript - Angular 2 : Validate child component form fields from the parent component

coder 2024-07-18 原文

问题陈述:

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

如何验证子组件 <input>来自父组件的字段 submit表格?

要求:

如果父组件的表单包含带有 input 的子组件模板中的组件,然后是这些 input如果从父组件提交,组件应该在点击时验证。

调查结果:

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

最佳答案

我们也可以使用模板驱动技术来实现它。在下面找到步骤:

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

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

    这里,parentForm是表单引用。

  • 使用@ViewChild 装饰器从父组件调用子组件方法,以在点击提交时传递提交按钮事件

    @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;
    }
    

图示:

关于javascript - Angular 2 : Validate child component form fields from the parent component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47981576/

有关javascript - Angular 2 : Validate child component form fields from the parent component的更多相关文章

随机推荐