Author -  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>

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY