【问题标题】:Angular 2 : Validate child component form fields from the parent componentAngular 2:验证来自父组件的子组件表单字段
【发布时间】:2018-06-07 11:20:45
【问题描述】:

问题陈述:

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

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

要求:

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

调查结果:

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

【问题讨论】:

  • 使用模型驱动形式。因为它将检查模型值而不是输入名称。
  • 我有一个非常相似的需求,但相当复杂,因为我必须验证层次结构表单、子级、嵌套组件等。使用响应式表单方法angular.io/guide/reactive-forms 很容易验证
  • 您是否面临插件问题,例如自动完成或 datepiker?
  • stackoverflow.com/a/47695731/4834833 阅读此内容。这是在给定父元素之后添加的一段代码。希望对你有所帮助。
  • 您能否发布一个示例应用程序以便我们了解更多上下文?

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


【解决方案1】:

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

图示:

【讨论】:

  • 很多代码来实现这一点。感觉这应该更简单。
  • 你能否在这篇文章中提供更简单的解决方案作为答案。
  • 其实我没有...我只是说应该更简单。虽然我目前正在阅读这篇看起来很有希望的文章。
  • 但是字段底部的错误消息在哪里?
猜你喜欢
  • 2023-03-13
  • 2022-09-15
  • 2019-05-06
  • 2018-08-30
  • 2017-12-31
  • 2019-01-29
  • 2017-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多