I am trying to build Reactive-Form spanning multiple components, something like this
<form [formGroup]="myForm" (ngSubmit)="onSubmitted()">
<app-names></app-names>
<app-address></app-address>
<app-phones></app-phones>
<button type="submit">Submit</button>
</form>
When I try to submit, I get empty object.
Stackblitz Here
Every component must be declared in one—and only one—Angular module. Open app.
Let us now create our form in the app. We have created a simple form with input tags having email id, password and the submit button. We have assigned type, name, and placeholder to it. In template driven forms, we need to create the model form controls by adding the ngModel directive and the name attribute.
A dynamic form requires an object model that can describe all scenarios needed by the form functionality. The example hero-application form is a set of questions —that is, each control in the form must ask a question and accept an answer. The data model for this type of form must represent a question.
Make the following changes
1.Use only one FormGroup
instead of creating the new FormGroup
for each component.
2.You have @Input
for FormGroup
however you are not passing as input.
3.Remove FormBuilder
from the child component.
<form [formGroup]="myForm" (ngSubmit)="onSubmitted()">
<app-names [myForm]="myForm"></app-names>
<app-address [myForm]="myForm"></app-address>
<app-phones [myForm]="myForm"></app-phones>
<button type="submit">Submit</button>
</form>
import { Component, OnInit, Input} from '@angular/core';
import { FormControl, FormGroup,FormBuilder } from '@angular/forms';
@Component({
selector: 'app-address',
templateUrl: './address.component.html',
styleUrls: ['./address.component.css']
})
export class AddressComponent implements OnInit {
@Input() myForm: FormGroup;
constructor(
private formBuilder: FormBuilder
) { }
ngOnInit() {
this.myForm.addControl("homeAddress" , new FormControl());
this.myForm.addControl("officeAddress" , new FormControl());
}
}
Make the similar changes for other components.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With