Joe Rattz
Joe Rattz

Reputation: 319

How in Angular.io to change input value from button click and cause input event to trigger

I'm trying to have a button clear a text input element in Angular 6.

<input #gf type="text" (input)="dt.filterGlobal($event.target.value, 'contains')">
<button (click)="gf.value = '';"></button>

In the markup above I have an input of type text that calls a filterGlobal method when data is entered into the input. Below that is a button that clears the value of the input when clicked. When clicke, the text disappears from the input but the input element's input event doesn't get triggered and therefore the filterGlobal method doesn't get called. Is there something wrong there? I would think changing the model's value would cause an input event to be triggered.

But if nothing is wrong, how can I fire the trigger from the button's click event? I could do this if I absolutely had to:

<button (click)="gf.value = ''; dt.filterGlobal($event.target.value, 'contains')"></button>

But now I'm duplicating code and if someone changes that input event handler without updating the click event handler...

Upvotes: 1

Views: 7389

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39432

With (input) your function is going to get called only when you input something in the text box. With the button click, the input value would change. But that isn't a result of a user input on the text field. Hence your function won't get called.

If you want to let your function get called in such a scenario, I think you should be binding to the (change) event. This will get called every time there's a change in the input field and you blur from it.

But that won't work if you blur first from the input field and then click the button.

In order to make it work in that case as well, consider calling dt.filterGlobal before doing gf.value but with gf.value instead of $event.target.value.

<input 
  #gf 
  type="text" 
  (input)="dt.filterGlobal($event.target.value, 'contains')">

<button 
  (click)="dt.filterGlobal(gf.value, 'contains'); gf.value = '';">
  Clear
</button>

Here's a Working StackBlitz Sample for your ref.

Upvotes: 1

Related Questions