Skip to content
Related Articles
Open in App
Not now

Related Articles

Angular forms FormGroupName Directive

Improve Article
Save Article
  • Last Updated : 06 Jan, 2023
Improve Article
Save Article

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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!