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/
In a model-driven form to reset the form we just need to call the function reset() on our myform model. The form now resets, all the input fields go back to their initial state and any valid , touched or dirty properties are also reset to their starting values.
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.
the resetForm() Method in Angular 2 The resetForm() method is a built-in Angular 2 method that clears the form values and resets them to their initial state. The resetForm() method can be invoked by passing a boolean as an argument. The form's fields and values will be cleared if the boolean argument is valid.
If you take a look at the reset button of the first form, Toggle submit, you will notice that it calls a method resetForm() on the click event of the button. Similarly the second form, Always submit, calls a method reset() . Both methods are called on the heroForm object.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With