1
votes

I realize there exists other questions regarding this issue but my situation is a bit different.

Our architecture team, in their infinite wisdom, decided to abstract away NgForms into a custom component. What I've run into recently is that attempting to use the NgModelGroup directive is causing Angular to complain "No provider for ControlContainer".

Referencing this Medium article: Angular: Nested template driven form, I've tried to use the 'viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]' in my host component. However, Angular then complains, "NullInjectorError: No provider for NgForm!"

As an example, here would be the structure of a component that is attempting to use this custom form component with the NgModelGroup directive:

<app-custom-form>

  <fieldset ngModelGroup="myGroup">
    <app-custom-input
      name="myValueName"
      placeholder="Input 1"
      [(ngModel)]="myValue"
    ></app-custom-input>

    <br>

    <app-custom-input
      name="myOtherValueName"
      placeholder="Input 2"
      [(ngModel)]="myOtherValue"
    ></app-custom-input>
  </fieldset>

</app-custom-form>

From my understanding of the article, this does make sense that Angular is having trouble because the NgModelGroup directive is attempting to find the ControlContainer within the parent. But what is considered the "parent" from the directive's point of view? It does not appear to be the 'app-custom-form' but rather the component that is attempting to use the directive?

If that's the case then to me it seems like I need to somehow provide the ControlContainer that exists within the app-custom-form component and re-direct that to the ngModelGroup directive. I'm not sure how to get the Angular DI to do this or if it's at all possible.

Here is a Github repo that demonstrates the problem.

1
By the way, I noticed another side effect of composing a form this way -- those inputs do not actually get added to the form's controls. So I question whether creating a custom form component is possible as it will not recognize its content childrens controls. - Jake Shakesworth

1 Answers

-2
votes

You have not added the @angular/forms FormsModule to your module’s import list.

Go to your app.module.ts and add this line to the imports:

import { FormsModule } from '@angular/forms';

and look for a line like this in your module definition:

imports: [ /* several import modules may be listed here */ ],

and add FormsModule like this (if there are already imports, add FormsModule to the list):

imports: [ FormsModule ],