6 ways to get input text value in Angular|Typescript

The form is a basic UI element in the Angular application that is displayed on the browser page to take user information.

The form contains multiple HTML input elements to take input from the user. a button allows the user to submit the form to the backend API and it calls the click binding event.

In Angular, View is an HTML template and controller is a typescript component. You can see my previous about Angular button click event example Reading input text is a basic concept every Angular developer needs to know.

This post covers multiple ways to read input value in Angular application. The following are different ways

Two-way data binding with ngModel directive

two-way data binding is an inbuilt feature introduced since the angular 2 versions.

It is used to share the data from component to template and vice versa.

This binding enables parent and child communication easier.

  • In one way binding, Running events listening from input entered in the form and ready to pass to component.
  • Update the form input value once the component changes its value.

Below is an example for reading the input text value on button click.

First, import FormModule in the AppModule file to work with 2-way binding.

app.module.ts:

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 HTML file,

add ngModel to the input field as given in the example.

Added the ngModel directive to the input element.

<p>
  <input type="text" id="username" name="username" [(ngModel)]="username" />
</p>
<div>{{username}}</div>

<button type="button" (click)="clickme()">Clickme</button>

In the component typescript file, declare a variable of type string

import { Component } from "@angular/core";
@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"],
})
export class AppComponent {
  username: string = "";
  clickme() {
    console.log("it does nothing", username);
  }
}

One-way binding with the local reference object

In the component template HTML, Added hash(#) local reference to the input form field. This reference holds an object of type HTMLInputElement.

<input type="text" id="username" name="username" #username />

pass the input local reference object value using ‘HTMLInputElement .value’ in the click event of a button.

<p><input type="text" id="username" name="username" #username /></p>
<div>{{username}}</div>

<button type="button" (click)="clickme(username.value)">Clickme</button>

Created a method clickme to catch click events in the component which accepts string parameters.

It is another way of reading input text values.

import { Component } from "@angular/core";
@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"],
})
export class AppComponent {
  clickme(username: string) {
    console.log("it does nothing", username);
  }
}

viewchild with local reference 2-way binding

First, define a local reference to an input text element in the HTML template view

<input type="text" id="username" name="username" #username />

In the Controller, declare viewChild in the component which is references the input element

  @ViewChild('username', {static: true}) usernameElement: ElementRef;
  myusername:string="";
  constructor(usernameElement: ElementRef){
    this.usernameElement=usernameElement;

  }

For Angular versions, less than 8, viewChild is annotated with the ElementRef type in the component to read the input value.

@ViewChild('username') usernameElement: ElementRef;

Finally, read the input value using ElementRef.nativeElement.value.

Here is the complete HTML template code

<br />
<div>Angular Read input value</div>
<br />
<p><input type="text" id="username" name="username" #username /></p>
<div>{{myusername}}</div>
<button type="button" (click)="clickme()">Clickme</button>

Controller typescript component on reading input element value on button click.

import { Component, ElementRef, ViewChild } from "@angular/core";
@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"],
})
export class AppComponent {
  @ViewChild("username", { static: true }) usernameElement: ElementRef;
  myusername: string = "";
  constructor(usernameElement: ElementRef) {
    this.usernameElement = usernameElement;
  }

  clickme() {
    this.myusername = this.usernameElement.nativeElement.value;
    console.log("it does nothing", this.myusername);
  }
}

read input value in typescript

It talks about how to read input text values in typescript.

First, declare the input element as follows.

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

In typescript component code, using native HTML API, document.getElementById returns HTMLInputElement and returns value property. getElementById is to select the HTML element with the id selector in javascript

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

formControlName to read input text element on button click

formControlName is an feature in [ReactiveFormsModule](#https://angular.io/api/forms/ReactiveFormsModule).

You have to import the ReactiveFormsModule module in app.module.ts and add these modules in the import section as described below.

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";

import { AppComponent } from "./app.component";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, FormsModule, ReactiveFormsModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

Following are the steps to make reactive form.

  • Add formControlName to the input element

    <input type="text" id="name" name="name" formControlName="name" />
    
  • Add form with formGroup name value

<form [formGroup]="nameForm">
  <p><input type="text" id="name" name="name" formControlName="name" /></p>
</form>

Here is the complete HTML code ```html
<br />
<div>Angular Read input value</div>
<br />

<form [formGroup]="nameForm">
  <p><input type="text" id="name" name="name" formControlName="name" /></p>
</form>
<button type="button" (click)="clickme()">Clickme</button>
<div>{{myusername}}</div>

In typescript controller code,

  • Declared public variable of type FormGroup which matched formGroup value in html
  • Initialised formgroup in the constructor using FormBuilder
  • retrieved using this.nameForm.get('name') syntax
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { AbstractControl, FormBuilder, FormControl, FormGroup } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  public nameForm:FormGroup;
  myusername: string = "";
  constructor( private formBuilder: FormBuilder) {
    this.nameForm = this.formBuilder.group({
      name: ''
    });
  }
  clickme() {
    this.myusername=this.nameForm.get('name')?.value;
    console.log('it does nothing', this.nameForm.get('name'));
  }
}

Input native events read values

By default HTML input elements provide native events and Angular also supports these events to read input text elements in the controller. Following events, we can use

  • onBlur event: client leaves from the input element

  • onChange: Fired, when the input element value changed

  • input event: fired when the user typed the data

  • key events: fired when a key is entered, also we have keyUp and keyDown events

    Following is an Angular onblur event example to read input element.

    html component

<br />
<div>Angular Read input value</div>
<br />

<p><input type="text" (blur)="blurEvent($event)" /></p>
<div>{{myusername}}</div>

controller component

import { Component, ElementRef, OnInit, ViewChild } from "@angular/core";
import {
  AbstractControl,
  FormBuilder,
  FormControl,
  FormGroup,
} from "@angular/forms";
@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"],
})
export class AppComponent {
  myusername: string = "";

  blurEvent(event: any) {
    this.myusername = event.target.value;
  }
}

Angular input form errors

The following are the errors that occurred when handling form input text fields in the Angular application.

Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’

This is a common error during 2-way data binding integrated using ngModel in input elements.

The solution is, please import the FormsModule module into the application module.

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

error NG8002: Can’t bind to ‘formGroup’ since it isn’t a known property of ‘form’

During form handling, if you are using any formControl and form group directives in an application, The following error happens.

Can’t bind to ‘formGroup’ since it isn’t a known property of ‘form’. The solution for this error is to importReactiveFormsModule` in your application and add this module in the import section of the application module.

import ReactiveFormsModule from @angular/forms

Conclusion

You learned different ways of reading input from the field in the Angular application. It includes errors and solutions with examples.