Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing an input text field in Angular2

Tags:

angular

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.

like image 652
Body Avatar asked Jan 05 '17 11:01

Body


People also ask

How do you clear a text field in HTML?

To clear all the input in an HTML form, use the <input> tag with the type attribute as reset.

How do you empty a field?

In the table design grid, select the field that you want to delete, and then press DEL.

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

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.


2 Answers

1. First Method

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

2. Second Method

  • use of [(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

like image 75
Pardeep Jain Avatar answered Sep 21 '22 17:09

Pardeep Jain


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> 
like image 44
Sudheer KB Avatar answered Sep 21 '22 17:09

Sudheer KB