Newbie
Newbie

Reputation: 827

Reset input value in angular 2

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/

Upvotes: 51

Views: 201932

Answers (12)

Fred3418
Fred3418

Reputation: 1

I recently had the exact same issue. I had an angular component with lot's of input fields and event select and option fields and i wanted to reset the component all at once.

Just running a reset function and resetting every element step by step seemed pretty elaborate and i searched for a better solution. Simply running this.ngOnInit won't reinitialize the component (at least in my case), it just simply runs your implemented code.

My first solution was to reassign the input fields values (my Input field values were binded to a variable in my component.ts), which kind of works, but only when you really change the value of the variable, otherwise angular won't detect any change an the rendered element will just stay the same.

So i came up with this solution: Just wrap an ng-container template around the content you want to reset and copy that one more time and use a toggle variable with the *ngIf directive to switch between the two of them:

HTML

<ng-container *ngIf="!displayToggle">
    <div #contentYouWantToDisplay>
        <input value="{{myNumber | number: '1.2-2'}}"
    </div>
</ng-container>

<ng-container *ngIf="displayToggle">
    <div #contentYouWantToDisplay>
        <input value="{{myNumber | number: '1.2-2'}}"
    </div>
</ng-container>

TS

resetContent(){
  displayToggle=!displayToggle;
  //other resets:
}

So when you call the resetContent function div will be rerendered and the user input will be reset.

Please notice that all variables will remain in the same state, so you might have to run some other resets (in my div the user also had the option toggle a button and then another div expanded, so i also had to reset the divs height in the resetContent function)

Upvotes: 0

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

Upvotes: 0

Rahul Singh
Rahul Singh

Reputation: 19632

you can do something like this

<input  placeholder="Name" #filterName name="filterName" />
<button (click) = "filterName.value = ''">Click</button>

or

Template

<input mdInput placeholder="Name" [(ngModel)]="filterName" name="filterName" >
<button (click) = "clear()'">Click</button>

In component

filterName:string;
clear(){
this.filterName = '';
}

Update

If it is a form

easiest and cleanest way to clear forms as well as their error states (dirty , prestine etc)

this.form_name.reset();

for more info on forms read out here

https://angular.io/docs/ts/latest/guide/forms.html

PS: As you asked question there is no form used in your question code you are using simple two day data binding using ngModel not with formControl.

form.reset() method works only for formControls reset call

A plunker to show how this will work link.

Upvotes: 79

syed
syed

Reputation: 636

  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);
    }
    

Upvotes: 0

AtLeastTheresToast
AtLeastTheresToast

Reputation: 387

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.

Upvotes: 3

Eduardo Vazquez
Eduardo Vazquez

Reputation: 2574

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>

Upvotes: 4

Durja
Durja

Reputation: 667

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

Upvotes: 0

sweetnsalt
sweetnsalt

Reputation: 9

In order to reset the value in angular 2 use:

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

Upvotes: 0

Site Antipas
Site Antipas

Reputation: 139

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

event.target.value = ""

Upvotes: 2

Sam Kelham
Sam Kelham

Reputation: 1467

I know this is an old thread but I just stumbled across.

So heres how I would do it, with your local template variable on the input field you can set the value of the input like below

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

@ViewChild() input: ElementRef

public clear() {
    this.input.NativeElement.value = '';
}

Pretty sure this will not set the form back to pristine but you can then reset this in the same function using the markAsPristine() function

Upvotes: 16

cotnic
cotnic

Reputation: 168

You should use two way binding. There is no need to have a ViewChild since it's the same component.

So add ngModel to your input and leave the rest. Here's your edited code.

<input mdInput placeholder="Name" [(ngModel)]="filterName" name="filterName" >

Upvotes: 0

Vipin
Vipin

Reputation: 79

Use @ViewChild to reset your control.

Template:

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

In Code:

@ViewChild('filterName') redel:ElementRef;

then you can access your control as

this.redel= "";

Upvotes: 7

Related Questions