Search code examples
angularangular2-formsangular-formsng-bootstrap

Angular2 ng-bootstrap nav with nested template-driven form


I've been using the answers (and the article within) from Angular2 nested template driven form to use child-nested form controls. Which is great until I try to use the child component within a Ng-Bootstrap Nav component, like so:

<ul ngbNav #nav="ngbNav" class="nav-tabs">
  <li ngbNavItem>
    <a ngbNavLink>One</a>
    <ng-template ngbNavContent>
      <nav-content-1></nav-content-1>
    </ng-template>
  </li>
</ul>

<form #form="ngForm">
  <div [ngbNavOutlet]="nav"></div>
</form>
@Component({
  selector: 'nav-content-1',
  template: `
    <h5>NavContent1</h5>
    <fieldset ngModelGroup>
      <label>Last Name</label>
      <input type="text" name="lastName" ngModel>
    </fieldset>
  `,
  viewProviders: [{ provide: ControlContainer, useExisting: NgForm }],
})
export class NavContent1Component {}

At this point, I receive the error NullInjectorError: No provider for NgForm.

I'm just starting to get the hang of providers, so bear with me. But it seems like the component declared in ngbNavContent is not being registered as a child of the parent component, and thus is not able to find any of the what-would-be inherited providers.

If that is the case, is there a way to directly reference the NgForm in the parent component from the components in the nav content?

StackBlitz


Solution

  • Thank you @yurzui for answering my question and showing me the folly of my ways. The form tag needed to be wrapped around the nav as well.

    <form #form="ngForm">
      <ul ngbNav #nav="ngbNav" class="nav-tabs">
        <li ngbNavItem>
          <a ngbNavLink>One</a>
          <ng-template ngbNavContent>
            <nav-content-1></nav-content-1>
          </ng-template>
        </li>
      </ul>
      <div [ngbNavOutlet]="nav"></div>
    </form>