I...">

Reset input value in angular 2

I have the following input field:

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

      

I want to clear the value when the clear button is clicked:

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

      

Function

app.component.ts :

filterName : string = null;
clearFilters() {

this.filterName = '';
}

      

Please let me know what is wrong with the above as it doesn't work for me.

Here's a jsfiddle https://jsfiddle.net/8fw8uq3x/

+15


source to share


6 answers


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 this is a form

the simplest and cleanest way to clean up forms as well as their error states (dirty, prestinous, etc.)

this.form_name.reset();

      

for more information on forms readable here

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

PS: As you asked the question, there is no form in your question code, you are using simple 2 day data binding using ngModel, not using FormControl.

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

Plunger to show how this link will work .

+28


source


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 controls as

this.redel= "";

      

+3


source


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

So how I would go about it, with your local template variable in the input field, you can set the value of the input as shown below

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

@ViewChild() input: ElementRef

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

      

Pretty sure this won't revert the form back to pristine, but you can reset this in the same function using the function markAsPristine()

+3


source


You have to use two way binding. There is no need to have a ViewChild as it is the same component.

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

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

0


source


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

event.target.value = ""

      

0


source


To reset a value in angular 2 use:

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

      

0


source







All Articles