Form in form. Can there be inheritance of form controls?
Update:
Indeed there is an easier way:
import { FormsModule, ControlContainer, NgForm, NgModel } from '@angular/forms';@Component({ ... viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]})export class ChildComponent {}
See also
Previous version:
I would say it's possible. For example you could add the following code to your
child.component.ts
import { NgForm, NgModel } from '@angular/forms';@Component({ selector: 'child-component', template: ` <input type="text" name="thirdControl" [(ngModel)]="thirdControl" /> <input type="text" name="fourthControl" [(ngModel)]="fourthControl" /> `})export class ChildComponent { @ViewChildren(NgModel) ngModels: QueryList<NgModel>; constructor(@Optional() private ngForm: NgForm) {} ngAfterViewInit() { if (this.ngForm) { this.ngModels.forEach(model => this.ngForm.addControl(model)); } }}
Angular DI system gives us the opportunity to get reference to parent NgForm
instance because angular dependency resolution algorithm starts with current node and goes up through tree of elements. In my example we can imagine the follwing tree
@NgModule providers | my-app | form / | \ input[text] input[text] child-component
So when we are requiring NgForm
token angular will search it in the next order
child-component || \/ form || \/ my-app || \/ @NgModule
On form element NgForm
directive is placed so when can get it. Also we can get any token that was declared on NgForm
directive within providers
array. And this rule applies to any node.
Then i just added child NgModel
directives manually to NgForm
so they should work together.
Angular has two kinds of forms, Template Driven and Reactive. What you want to do isn't possible with Template Driven forms, you'll need to look into Reactive Forms
In general it works by creating a form object in the component, and using it in the template. Angular says this is actually more flexible and easier to test, but I think the syntax is a lot harder to wrap your head around.
You'll want this in your parent component:
myForm: FormGroup; constructor(private fb: FormBuilder) { // <--- inject FormBuilder this.createForm(); } createForm() { this.myForm = this.fb.group({ firstControl: '', secondControl: '', thirdControl: '', fourthControl: '' }); }
Your parent template would look something like this:
<form [formGroup]="myForm" novalidate><input type="text"formControlName="firstControl" /> <input type="text" formControlName="secondControl" /> <child-component [parentFormGroup]="myForm"></form>
And your child will accept the form group as an input, and the template will look something like this:
<div class="form-group" [formGroup]="parentFormGroup"> <input type="text" formControlName="thirdControl" /> <input type="text" formControlName="fourthControl" /></div>