Submitting Angular Forms

  • FormsModule is required for use Forms functionality of Angular.(Import is required)
  • ngModel directive is used to indicate Angular that this form input is actually a control of my form.
  • We need to provide the name attribute to the form input so the data of that input is stored while submitting the form.
  • When a normal form submit happens the page is redirect to the action that is mentioned in the form tag but in Angular we use directive (ngSubmit)=”methodCall()” method name is added to ngSubmit which is mentioned in the ts file of that component.
  • In the below example we have passed a local reference of form tag into the ts function call and printed the complete DOM of form tag in console

Below is the example of it :

First add FormsModule in the app-module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Below code in app-component.html file

<link href="//" rel="stylesheet" id="bootstrap-css">
<script src="//"></script>

<script src="//"></script>

<div class="container">
    <div class="row">
        <div class="col-md-3"></div>
        <div class="card border-primary mb-3">
          <div class="card-header" style="background-color: #007BFF; color : white">
            Registeration Form
          <div class="card-body">
              <form (ngSubmit)="onSubmit(f)" #f>
                  <div class="form-row">
                      <div class="form-group">
                          class="form-control form-control-sm col-md-12"
                  <div style="text-align:center">
                    <button type="submit" class="btn btn-primary" >Click Me</button>

Create a html form using below code in app-component.ts

import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {

  title = 'RegForm';
  onSubmit(form: HTMLFormElement) {

Output looks like below :

Leave a Comment