How to access Dynamically added control in child c

2019-08-20 04:54发布

问题:

I have a common form which I am needed to call from multiple places with dynamic controls within it.

My question is how can I access the sub form with dynamic controls from the parent form. I have a formGroup variable containing a child sub form. I want that variable to get initialized when a button is clicked from the parent form.

 ngOnInit(){
  this.parentForm = this.fb.group({
   firstName:['',[Validators.required]],
   childForm:this.fb.group({}),     //Is it possible to initialize this from child 
  })
 }

onSubmit(){
console.log(this.parentForm.getRawValue()) ;   
}

I have used @ViewChild to access the sub form from the parents and this gives me access to the entire sub component I would like to know is this the only way of doing so or if there an alternate option to achieve the same.I have seen samples on the web where @Input is used to pass the sub-form from the parent to the child but in my case I have to create the dynamic form from the child only. So far I have tried with stackblitz link.