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

Roh*_*dal 8 javascript typescript angular2-forms angular-validation angular

问题陈述 :

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

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

要求:

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

发现 :

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

Roh*_*dal 12

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

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

    <button type="button" (click)="enterForm(parentForm)">Submit</button>
    
    Run Code Online (Sandbox Code Playgroud)

    这里parentForm是表格参考.

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

    @ViewChild('validateChildComponentForm') private ChildComponent: ChildComponent;
    
    Run Code Online (Sandbox Code Playgroud)
  • 使用@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.
        }                
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 现在在子组件方法中,我们将检查是否提交了父表单并且子组件表单有效,然后发出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);
            }
        }
    } 
    
    Run Code Online (Sandbox Code Playgroud)
  • 现在在父组件中,我们将获得isChildFormValid值.

    private isChildFormValid(formValid: any) {
        this.childFormValidCheck = formValid;
    }
    
    Run Code Online (Sandbox Code Playgroud)

图示:

在此输入图像描述

  • 很多代码来实现这一点。感觉这个应该更简单。 (2认同)
  • 您能否在本文中提供您更简单的解决方案作为答案。 (2认同)