首页 文章

如何从父组件OnSubmit Angular 4触发子组件的验证?

提问于
浏览
1

我有这样的形式,在父母我包括多个子组件,每个子组件是formgroup . 现在我需要在用户单击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

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

1 回答

  • 0

    将Formcontrol传递给Parent作为OUTPUT,然后通过在按钮单击中调用函数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);
          }
        });
    }
    

相关问题