1

How to add template-driven control to ngForm?

For example I have form with two components:

@Component({
    selector: 'parent-form',
    template: '<form #form="ngForm">
      <input required [(ngModel)]="model.foo" name="foo">
      <child-form [model]="model"></child-form>
    </form>',
    directives: [ REACTIVE_FORM_DIRECTIVES, ChildFormComponent ]
})
export class ParentFormComponent {
    public model: MyModel = new MyModel();
}

@Component({
    selector: 'child-form',
    template: '<fieldset>
      <input required [(ngModel)]="model.bar" name="bar">
    </fieldset>',
    directives: [ REACTIVE_FORM_DIRECTIVES ]
})
export class ChildFormComponent {
    @Input() public model: MyModel;
}

How to add "bar" control from "child form" to "form" in "parent form"?

Update: I found similar feature request.

2 Answers 2

4

As hotfix you may use "RegisterFormModelDirective":

import { Directive, ElementRef, Input, OnInit } from '@angular/core';
import { NgModel, NgForm } from '@angular/forms';

@Directive({
    selector: '[registerForm]'
})
export class RegisterFormModelDirective implements OnInit {
    private el: HTMLInputElement;

    @Input('registerForm') public form: NgForm;
    @Input('registerModel') public model: NgModel;

    constructor(el: ElementRef) {
        this.el = el.nativeElement;
    }

    ngOnInit() {
        if (this.form && this.model) {
            this.form.form.addControl(this.model.name, this.model.control);
        }
    }
}

And this directives:

<input [(ngModel)]="myValue" minlength="10" #myInput="ngModel" #myComp
  name="childValue" [registerForm]="form" [registerModel]="myInput">

See plunkr demo: https://plnkr.co/edit/GG2TVHHHGbAzoOP5mIRr?p=preview

If you have "EXCEPTION: Expression has changed after it was checked. Previous value: 'false'. Current value: 'true'", change code:

public ngOnInit() {
    if (this.form && this.model) {
        this.form.form.registerControl(this.model.name, this.model.control);
        this.form.addControl(this.model);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

As a side note to Alexey's answer, you should add OnDestroy handler to deattach the input from form control. This is especially required if you're using the input with *ngIf.

public ngOnDestroy() {
    if (this.form && this.model) {
        this.form.removeControl(this.model);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.