Open In App

Angular forms FormGroupName Directive

In this article, we are going to see what is FormGroupName in Angular 10 and how to use it. The FormGroupName is used to sync a nested FormGroup to a DOM element.

Syntax:



<form [FormGroupName] ="details">

Exported from:

Selectors:



 

Approach: 

Example:




import { Component, Inject } from '@angular/core';
  import { FormGroup, FormControl, FormArray } from '@angular/forms'
  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: [ './app.component.css' ]
  })
  export class AppComponent  {
    form = new FormGroup({
      details: new FormGroup({
        name: new FormControl(),
        email: new FormControl()
      })
    });
  
    get name(): any {
      return this.form.get('details.name');
    }
    get email(): any {
      return this.form.get('details.email');
    }
    
    onSubmit(): void {
      console.log(this.form.value); 
    }
    
  }




import { NgModule } from '@angular/core';
  
// Importing forms module
import { FormsModule, ReactiveFormsModule  } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } 
    from '@angular/platform-browser/animations';
  
import { AppComponent }   from './app.component';
   
@NgModule({
  bootstrap: [
    AppComponent
  ],
  declarations: [
    AppComponent
  ],
  imports: [
    FormsModule,
    BrowserModule,
    BrowserAnimationsModule,
    ReactiveFormsModule
      
  ]
})
export class AppModule { }




<br>
<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <div formGroupName="details">
    <input formControlName="name" placeholder="Name">
    <input formControlName="email" placeholder="Email">
  </div>
  <br>
    
  <button type='submit'>Submit</button>
  <br><br>
</form>

Output:

Reference: https://angular.io/api/forms/FormGroupName


Article Tags :