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>
Functionapp.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/
source to share
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 .
source to share
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()
source to share