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:
<input type="text" [(ngModel)]="name" required />
<button (click)="handleClear()">Clear input field</button>
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:
<input type="text" #name required />
<button (click)="handleClear()">Clear input field</button>
#name
is the reference added to the aboveinput
field.
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.
<input type="text" #name required />
<button (click)="name.value=' '">Clear input field</button>