Nested Formgroup Example
In this example, I will show that how we can add form group into another form group or how we can create nested form groups in angular 4.
Step 1: Create a new component(reactiveformex.component.ts) and add following code.
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators , ReactiveFormsModule } from '@angular/forms'; @Component({ selector: 'app-reactiveformex', templateUrl: './reactiveformex.component.html', styleUrls: ['./reactiveformex.component.css'] }) export class ReactiveformexComponent implements OnInit { EMAIL_REGEX = "[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*"; registrationForm: FormGroup; constructor() { } ngOnInit() { this.registrationForm = new FormGroup({ fname: new FormControl('', Validators.required), lname: new FormControl('', Validators.required), email: new FormControl('', [Validators.required, Validators.pattern(this.EMAIL_REGEX)]), address: new FormGroup({ city: new FormControl(''), state: new FormControl('', Validators.required) }) }); } onSubmit(formvalue) { console.log(formvalue); console.log(this.registrationForm.value); } }
Step 2:
Add following code in reactiveformex.component.html
<p> reactiveformex works! </p> <form novalidate [formGroup]="registrationForm" (ngSubmit)="onSubmit(registrationForm.value)"> <input type="text" class="form-control" formControlName="fname" > <div class="error-message" *ngIf="registrationForm.get('fname').touched && registrationForm.get('fname').hasError('required')"> The First name is required. </div> <input type="text" class="form-control" formControlName="lname" > <div class="error-message" *ngIf="registrationForm.get('lname').touched && registrationForm.get('lname').hasError('required')"> The Last name is required. </div> <input type="email" class="form-control" formControlName="email"> <div class="error-message" *ngIf="registrationForm.get('email').touched && registrationForm.get('email').hasError('required')"> The email is required. </div> <div class="error-message" *ngIf="registrationForm.get('email').touched && registrationForm.get('email').hasError('pattern')"> The email format should be <i>yogeshdotnet@gmail.com</i> </div> <div formGroupName="address"> <input type="text" class="form-control" formControlName="city"> <br/> <select class="form-control" formControlName="state"><option value="RJ">Rajasthan</option><option value="UP">Uttar Pradesh</option></select> <div class="error-message" *ngIf="registrationForm.get('address').get('state').touched && registrationForm.get('address').get('state').hasError('required')"> The State is required. </div> </div> <button type="submit" class="btn btn-secondary" [disabled]="registrationForm.invalid">Submit</button> </form>
Step 3. Add reference to this component into app.component.html and run program (ng serve –o)
Output