6 ways to get input text value in Every Angular/typescript developer should know


In Angular application,Form is an basic ui element displayed on browser page to accept user information. Form contains multiple html input elements to take input from the user, button enables users to click the event. In Angular, View is html template and controller is an typescript component.

Reading input text is basic concept every Angular developer need to know.

This post covers multiple ways to read input value in Angular application. Following are differnt ways

Two way data binding with ngModel directive

two-way data binding is an important inbuilt feature introduced since angular 2 version.

It is very useful to share the data from component to template vice versa and enables parent and child communication easier.

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

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

First, import FormModule in 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 fielda as given in the example.

Added the ngModel directive to input element.

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

<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 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 click event of an button

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

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

Created a method clickme to catch click event in the component which accepts string parameter

This is another way of reading input text value

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 an local references to an input text element in html template view

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

In the Controller, declare viewChild in component which is an referencing 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 annoted with ElementRef type in component to read the input value.

@ViewChild('username') usernameElement: ElementRef;

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

Here is the complete html template code

<br>
<h1>Angular Read input value</h1><br>
<p><input type="text" id="username" name="username" #username></p>
<h1> {{myusername}}</h1>
<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

This talks about how to read input text value in typescript.

First declare input element as follows

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

In typescript component code, using native html API, document.getElementById returns HTMLInputElement and return value property. getElementById is to select the html element with 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 ‘ReactiveFormsModule’ module in app.module.ts and add these module in 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 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>
<h1>Angular Read input value</h1><br>

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

In typescript controller code,

  • Declared public variable of type FormGroup which matched formGroup value in html
  • Initilized formgroup in 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 provides native events, Angular also supports this events to read input text elements in controller. Following events we can use

  • onBlur event: client leaves from input element

  • onChange: Fired, when input element value changed

  • input event: fired when user typed the data

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

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

    html component

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

    <p><input type="text" (blur)="blurEvent($event)">

    </p>
<h1> {{myusername}}</h1>

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 occured when handling form input text fields in Angular application

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

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

The solution is, please import FormsModule module into 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 import ReactiveFormsModule` in your application and add this module in import section of application module.

import ReactiveFormsModule from @angular/forms 
Similar Posts