Open In App

Angular forms FormGroupName Directive

Last Updated : 06 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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:

  • ReactiveFormsModule

Selectors:

  • [FormGroupName]

 

Approach: 

  • Create the Angular app to be used
  • In app.component.ts make an object that contain value for the input.
  • In app.component.html use FormGroupName to get values.
  • Serve the angular app using ng serve to see the output.

Example:

app.component.ts




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); 
    }
    
  }


app.module.ts




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 { }


app.component.html




<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



Next Article

Similar Reads

three90RightbarBannerImg