Why is this method not working when I try to clear the text field?
<div> <input type="text" placeholder="Search..." [value]="searchValue"> <button (click)="clearSearch()">Clear</button> </div> export class App { searchValue:string = ''; clearSearch() { this.searchValue = ''; } }
What I'm expecting: since I'm passing a property for search value, when I click the button, it should get the updated value which is processed in clearSearch()
function.
I also noticed that if I set a default value to searchValue
, clearSearch()
function works, but only once.
Please check my plunker.
To clear all the input in an HTML form, use the <input> tag with the type attribute as reset.
In the table design grid, select the field that you want to delete, and then press DEL.
The reset() method resets the values of all elements in a form (same as clicking the Reset button). Tip: Use the submit() method to submit the form.
you have to assign null or empty string here
this.searchValue = null; //or this.searchValue = ' ';
Working Plunker
because no event is being fired from angular change detection. so you have to assign some value either null or string with space
[(ngModel)]
it should work with ngModel
.why ?
because as you did binding with value
attribute which is only property binding not event binding. so angular doesn't run change detection because no event relevant to Angular is fired. If you bind to an event then Angular runs change detection and the binding works and value should be changes.
see working example of same with ngModel
Working Example with ngModel
You can just change the reference of input value, as below
<div> <input type="text" placeholder="Search..." #reference> <button (click)="reference.value=''">Clear</button> </div>
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