Reset input value in angular 2

Viewed 157958

I have the following input field :

<input mdInput placeholder="Name" #filterName name="filterName" >

I want to clear value on click of clear button :

<button (click)="clearFilters()">Clear</button>

app.component.ts function :

filterName : string = null;
clearFilters() {

this.filterName = '';
}

Please let me know whats wrong with above as its not working for me.

Here the jsfiddle https://jsfiddle.net/8fw8uq3x/

11 Answers

You can use the event.target.result to reset the input from a component directly.

event.target.value = ""

If you want to clear the input by using the HTML ONLY, then you can do something like this:

<input type="text"
       (keyup)="0"
       #searchCollectorInput
       class="search-metrics"
       placeholder="Find">

Notice the importance of (keyup)=0 and the reference to the input of course.

Then reset it like this:

<span *ngIf="searchCollectorInput.value.length > 0"
      (click)="searchCollectorInput.value = ''"
      class="fa fa-close" ></span>

Working with Angular 7 I needed to create a file upload with a description of the file.

HTML:

<div>
File Description: <input type="text" (change)="updateFileDescription($event.target.value)" #fileDescription />
</div>

<div>
<input type="file" accept="*" capture (change)="handleFileInput($event.target.files)" #fileInput /> <button class="btn btn-light" (click)="uploadFileToActivity()">Upload</button>
</div>

Here is the Component file

  @ViewChild('fileDescription') fileDescriptionInput: ElementRef;
  @ViewChild('fileInput') fileInput: ElementRef;

ClearInputs(){
        this.fileDescriptionInput.nativeElement.value = '';
        this.fileInput.nativeElement.value = '';
}

This will do the trick.

In order to reset the value in angular 2 use:

this.rootNode.findNode("objectname").resetValue();

If you want to clear all the input fields after submitting the form, consider using reset method on the FormGroup.

  1. check the @viewchild in your .ts

    @ViewChild('ngOtpInput') ngOtpInput:any;
    
  2. set the below code in your method were you want the fields to be clear.

    yourMethod(){
        this.ngOtpInput.setValue(yourValue);
    }
    
TS Code
export class AppComponent {

 value:any;
 
 clickHandler()
  {
    this.value="";}
  }
HTML code
<div>
    <button (click)="clickHandler()" >Submit</button>
    <input type="text" [(ngModel)]="value">
</div>


 

then you need implement this to your module:

import { FormsModule } from '@angular/forms';
after that add this: FormsModule to imports section in module
Related