angular 2 model driven nested form components

Thanks for the answers guys. In the end we created two components, a custom-form component and a custom-input component.

We nest as many custom-input components as we need inside the custom-form component and the custom-form component uses @ContentChildren to identify and register all the child custom-input components.

This way we don't have to pass the form into every input, and we don't have a mess of nested form groups for every input.

// Each CustomInputText component exposes a FormControl and 
// a control definition which has additional info about the control
@ContentChildren(CustomInputText, {descendants: true})
public customInputComponents: QueryList<CustomInputText>;

private initialised;

public ngAfterContentChecked() {
  // Only initialise the form group once
  if (!this.initialised) {
    this.initialised = true;
    this.customInputComponents.forEach((input)=>{
        this.formGroup.addControl(input.controlDefinition.id, input.formControl); 
    });
  }
}

You can @Input your loginForm into nested component, as let's say parentForm. Then register nested formGroup to parentForm on child component init, and unregister it on child component destroy.


What I did in my case (nested dynamic form as well) is somehow similar to Marcin's response.

I'm passing existing FormGroup as parentForm and my Component's view looks like this:

<fieldset [formGroup]="parentForm">
    <label *ngIf="label" [attr.for]="key">{{label}}</label>
    <input [id]="key" [type]="type" [formControlName]="key" />
</fieldset>

It suits my needs. Hope it can help you as well.

UPDATE: I've created a library for speeding up dynamic forms creation. You can take a look to figure out how I use the technique from this answer: https://www.npmjs.com/package/dorf