【问题标题】:how to trigger a validation of child component from parent component OnSubmit Angular 4?如何从父组件 OnSubmit Angular 4 触发对子组件的验证?
【发布时间】:2018-04-27 00:23:13
【问题描述】:

我有这样的表单,在父级中我包括多个子组件,每个子组件都是表单组。现在我需要在用户单击 OnSubmit 时检查父表单上的所有这些子表单验证。

我应该如何在提交时从父级触发子表单验证。我在每个子组件中都使用了 FormBuilder。

当用户单击子字段时,我可以进行验证,但如果用户没有输入任何内容或触摸任何内容并尝试提交不显示错误的验证。

parent.component.html

<form>
    <child1></child1>
    <child2></child2>
    <child3></child4>
    <child4></child4>
''''
''''
''''
</form>

child1.component.html

<div formgroup="child1group">
      <div formarray= "child1array">
      ....
      ...
      ...
      </div>
</div

child2.component.html

<div formgroup="child2group">
      <div formarray= "child2array">
      ....
      ...
      ...
      </div>
</div

请有人告诉我如何在 angular 4 上进行此验证?

【问题讨论】:

    标签: angular validation typescript


    【解决方案1】:

    将 Formcontrol 作为 OUTPUT 传递给 Parent,然后通过在按钮单击中调用函数 SaveConsole() 进行验证

    child1.component.ts

    @Output() public childControls = new EventEmitter();
    
     public ngOnInit() {
            this.childControls.emit(this.child1group);   
            this.child1group.valueChanges.subscribe(() => {
                this.childControls.emit(this.child1group);
            });
      }
    

    parent.component.html

       <form>
            <child1 (childControls)="child1Control = $event"></child1>
             <button (Click)=SaveConsole()> Submit </butto>
       </form>
    

    parent.ts

       public child1Control: FormGroup;
       public SaveConsole() {
              if (this.child1Control.valid) {
                // SAVE FORM
              } else {
                this.validateAllFormFields(this.child1Control);  
              }
          }
         public validateAllFormFields(formGroup: FormGroup) {
          Object.keys(formGroup.controls).forEach(field => {
          const control = formGroup.get(field);
          if (control instanceof FormControl) {
            control.markAsTouched({ onlySelf: true });
          } else if (control instanceof FormGroup) {
            this.validateAllFormFields(control);
          }
        });
    }
    

    【讨论】:

    • 如果我有 20 个子组件,那么我必须在 SaveConsole() 中检查 20 次这些控制器的验证。恕我直言,这是一个不好的方法
    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 2018-08-12
    • 2016-11-27
    • 1970-01-01
    相关资源
    最近更新 更多