0

I have a custom control that I have created.

  1. It accepts formControlName="first_name"
  2. it is wrapped in a <form [formGroup]="userProfileForm">

It works great.

Is it possible to reference the formGroup from within the custom control's class without adding and input:

@Input() formGroup: FormGroup;

2 Answers2

0

Put a template name on your form element:

<form [formGroup]="userProfileForm" #my_form>

Then, in your component, you can get this element as a member variable:

@ViewChild('my_form') formVariable;

Now, you can access the formGroup with:

this.formVariable.formGroup

from within the component, or

formVariable.formGroup

from within the template.

Edit after comment: you don't want tight coupling

What you describe amounts to inter-components communication: you want components, embedded or not, to exchange informations. The usual and best way to go is with a service and a Subject mechanism. See here in the official Angular docs.

Qortex
  • 7,087
  • 3
  • 42
  • 59
  • That is another way I guess, but still messy and perhaps less reusable than @input. I am trying to avoid the tight coupling. The goal here is to discover in some way, I thought it must be possibles to infer the formGroup. I am about to dive deeper and will update if i find something. –  Apr 07 '19 at 13:41
  • Ok, I see. I edited the answer to help you with that. – Qortex Apr 07 '19 at 14:15
0

from this stackoverflow answer you can inject in the constructor:

constructor(el:ElementRef,@Host() @SkipSelf() private control:ControlContainer)

So, in ngOnInit in control.control you has the FormGroup

ngOnInit()
    {
      console.log(this.control.control.value)
    }
Eliseo
  • 50,109
  • 4
  • 29
  • 67