Open In App

Angular forms FormGroupDirective

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see what is FormGroupDirective in Angular 10 and how to use it.

FormGroupDirective is used to Bind an existing FormGroup to a DOM element.

Syntax:

<form [FormGroup] ="name">

Exported from:

  • ReactiveFormsModule

 

Selectors:

  • [FormGroup]

Approach: 

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

Example 1:

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({
      name: new FormControl()
    });
  
    get name(): any {
      return this.form.get('name');
    }
    
    onSubmit(): void {
      console.log(this.form.value); 
    }
    
  }


app.component.html




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


Output:

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



Last Updated : 02 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads