Different ways to get form data in Angular Component

    Sep 09, 2021       by Pankaj Kumar
different-ways-to-get-form-data-in-angular-component.jpg

While working with any type of front-end application it is very common task to get value from form and perform some operations on it. If we talk specifically about Angular then we have different ways to get the form value. In this article, We will see the different ways using which form value can be received in Reactive as well as template-driven.

Ways to get form value in Angular application

  1. Using formControlName (Reactive Form)
  2. Using document object
  3. Using local reference object
  4. Using ngModel (Template-driven Form)
  5. Using ViewChild
  6. Using Input native events

1. Using formControlName (Reactive Form)

Reactive forms provide a model-driven approach to handling form inputs whose values change over time. formControlName is used while working with Reactive Form in angular. To use formControlName, We need to follow below steps.

import ReactiveFormsModule in App module(app.module.ts)

 

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

 

Let's have a look at the code inside template file

 

 
<form [formGroup]="userForm">
    <p><input type="text" id="first_name" name="first_name" formControlName="first_name">
    </p>
 </form>
 <button type="button" (click)="setValue()">Go</button>
 <h1> {{first_name}}</h1>
 

 

Code inside typescript/controller file

 
 import { ComponentElementRefOnInitViewChild } from '@angular/core';
import { AbstractControlFormBuilderFormControlFormGroup } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  public userForm:FormGroup// variable is created of type FormGroup is created
  first_namestring = ""// Variable is created to show the input value below the button
  constructorprivate fbFormBuilder) {
    // Form element defined below
    this.userForm = this.fb.group({
      first_name: ''
    });
  }
  setValue() {
    this.first_name=this.userForm.get('first_name')?.value// input value retrieved
  }
}
 

 

2. Using HTML DOM

 With HTML DOM, form data can be received in the typescript controller. 

<input type="text" id="first_name" name="first_name" />

 

document.getElementById returns HTMLInputElement and return value property.

this.first_name = (<HTMLInputElement>document.getElementById("first_name")).value;

 

3. Using local reference object

It is one of the easiest and quickest way to get the form data into component file. For it, We mainly add hash(#) local reference to the input form fields. This reference holds an object of type HTMLInputElement.

 
<div><input type="text" id="first_name" name="first_name" #first_name></div>
<h3> {{first_name}}</h3>
 
<button type="button" (click)="setValue(first_name.value)">Go</button>
 

 

In the above code, An input field and a button is part of the form.Now let's have look inside the ts file how can we access the passed data into the setValue function parameter.

 

 
import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
 
export class AppComponent {
  first_namestring = '';
  setValue(first_name:string) {
    console.log('First Name: ',first_name);
  }
}
 

 

By following only the above simple steps data can be sent to the component. For using the above approach, We don't need to import any extra packages.

 

4. Using ngModel 

while working with the template-driven modules, ngModel is mostly used to get the form data. It provides two way data binding, which means using this data can be shared from component to template and vice-versa. See the example below:

At first, formModule is needed to import in app.module.ts file

 

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

 

In the Component template file, We will use ngModel for data binding and a button on click which a function is called inside the component.

 

 
<div><input type="text" id="first_name" name="first_name" [(ngModel)]="first_name"></div>
<h3> {{first_name}}</h3>
 
<button type="button" (click)="setValue()">Click here</button>
 

 

Now, let's have a look inside the ts file.

 

 
import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
 
export class AppComponent {
  first_namestring = '';
  setValue() {
    console.log('First Name: ',first_name);
  }
}
 

 

By following the above steps one can easily get form data into components.

 

5. Using ViewChild

Have a look in code inside template

 
<div><input type="text" id="first_name" name="first_name"  #first_name></div>
<h3> {{first_name}}</h3>
 
<button type="button" (click)="setValue()">Click here</button>
 

 

Code inside controller file

 

 
import { ComponentElementRefViewChild } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  @ViewChild('first_name', { static: true }) firstNameElementElementRef;
  first_name_valstring = "";
  constructor(nameElementElementRef) {
    this.firstNameElement = nameElement;
 
  }
 
  setValue() {
    this.first_name_val = this.firstNameElement.nativeElement.value;
    console.log('First name value:'this.first_name_val);
  }
}
 

 

6. Using Input native events

It is also a very quick solution to get form data into the controller file, But here we get the complete object of the input field so it is not recommended in spite local reference object is recommended for getting form data.

 

<input type="text" id="first_name" name="last_name" (onChange)="showValue($event)" />

<h2>{{first_name}}</h2>

 

 code in ts file to get the value and set in a variable

showValue(event: any){

  this.first_name = event.target.value;

}

 


Find other similar Articles here: