mrshickadance
mrshickadance

Reputation: 1251

Angular Add Control to form from child component

In Angular 2, I have a child component that includes an input. I want to add this input (control) to the parent components form (NgForm).

I am currently using Template Driven Forms for simplicity.

I saw this answer, but think it is likely outdated?: Angular 2 Add control to parent component's form

Child Component Template: formInputName is an input binding so that I can reuse this component, and add the 'name' property dynamically.

<input class="text-input" [name]="formInputName" [id]="formInputName" type="text" [(ngModel)]="searchValue"
            (change)="onChange(searchValue)"
            (blur)="onBlur()"
            (focus)="onFocus()"
            [required]="isRequired">

On the parent component I have an instance of the form:

    @ViewChild('testForm') testForm: NgForm;

How can I add the child components control to this instance of NgForm? I'm not sure how to do it with addControl. Not sure what I need to add in the template, or how to do it programmatically in the controller.

Plunker: https://plnkr.co/edit/rDluyJduyHF7vclK9wRE?p=preview

Upvotes: 3

Views: 4197

Answers (1)

amal
amal

Reputation: 3170

Could you try this, and see if it is working,

Child component

@Output() childControl = new EventEmitter<NgModel>(); // import { NgModel } from '@angular/forms';
@ViewChild('myControl') myControl: NgModel;

ngAfterViewInit() {
 this.childControl.emit(myControl); // emitting the control to the parent to be picked up there and added to the main form
}

Child template

<input #myControl="ngModel" class="text-input" [name]="formInputName" [id]="formInputName" type="text" [(ngModel)]="searchValue"
            (change)="onChange(searchValue)"
            (blur)="onBlur()"
            (focus)="onFocus()"
            [required]="isRequired">

Parent template

<child-component (childControl)="childControlReady($event)"></child-component>

Parent component

childControlReady(control: NgModel) {
 this.testform.addControl(control);
}

Upvotes: 8

Related Questions