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

时间:2017-12-26 17:07:56

标签: javascript angular typescript angular2-forms angular-validation

问题陈述:

父组件中包含<form>标记和一些<input>标记,子组件也有一些<input>标记,父组件有一个<submit>我们正在验证表单提交表格的字段。

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

要求:

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

调查结果:

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

1 个答案:

答案 0 :(得分:8)

我们也可以使用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;
    }
    

图示:

enter image description here

相关问题