2017-11-14 13 views
1

私はこのようなフォームを親に持っています。複数の子コンポーネントを含んでいます。各子コンポーネントはformgroupです。今私はOnSubmitをクリックすると、親フォーム上のこの子フォーム検証をすべてチェックする必要があります。親コンポーネントから子コンポーネントの検証をトリガする方法OnSubmit角4?

送信時に、子フォームの検証を親からトリガーする方法を教えてください。 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でこの検証を行う方法を教えてください。

答えて

0

OUTPUTとして親にFormcontrolを渡し、その後は

child1.component.tsをクリックし、ボタンに機能SaveConsole()を呼び出すことによって、検証を行う

@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); 
     } 
    }); 
} 
関連する問題