Skip to content

Instantly share code, notes, and snippets.

@navix
Last active May 13, 2019 11:51
Show Gist options
  • Save navix/8a56e4eec7cb2ec4a0eacc0c58ae3fd4 to your computer and use it in GitHub Desktop.
Save navix/8a56e4eec7cb2ec4a0eacc0c58ae3fd4 to your computer and use it in GitHub Desktop.
Bind ngModel controls to ngForm from parent component

Bind ngModel controls to ngForm from parent component

This allows you to split a template-driven form on components.

Create formProvider directive to proxy ngModel injector from parent to child:

import { Directive, SkipSelf, forwardRef } from '@angular/core';
import { ControlContainer, Form } from '@angular/forms';

@Directive({
  selector: '[formProvider]',
  providers: [
    {
      provide: ControlContainer,
      useFactory: (parent) => parent,
      deps: [[new SkipSelf(), ControlContainer]],
    }
  ]
})
export class FormProviderDirective {
}

Use it in a child component:

<ng-container formProvider>
  <input name="inChild" [(ngModel)]="form.inChild">
</ng-container>

Be aware

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment