by Sai gowtham

Clearing the input (text) field value in Angular

In this tutorial, we are going to learn about how to clear the input field value by clicking a button in angular.

We mostly clear the input field values after submitting a form or resetting the wrong information inside the form.

Using the ngModel

If you are using [(ngModel)] directive to control your form input fields, then you can clear it by setting an empty string (' ') to the ngModel control property.

Example:

app.component.html
<input type="text" [(ngModel)]="name" required />
<button (click)="handleClear()">Clear input field</button>
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  handleClear(){
    this.name = ' ';  }
}

Using the element reference

We can also clear it by adding a reference to the input field and access that element inside the app component by using @ViewChild() decorator.

Example:

app.component.html
<input type="text" #name required />
<button (click)="handleClear()">Clear input field</button>

#name is the reference added to the above input field.

app.component.ts
import { Component , ViewChild} from '@angular/core';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
 @ViewChild('name') inputName; // accessing the reference element
  handleClear(){
      // clearing the value    this.inputName.nativeElement.value = ' ';
  }
}

or we can clear it, by accessing a reference element inside the HTML template like this.

app.component.html
<input type="text" #name required />
<button (click)="name.value=' '">Clear input field</button>

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course