Mike Me
Mike Me

Reputation: 2392

Call a function every time a user updates an input text field in Angular

My objective is to call a function whenever an user modifies in an input text field.

In my example every time the user adds or deletes a character in the text field it should call didModify() in synchronous thus adding 1 to changeCounter.

My .html:

<div class="pb-1">
  <input maxlength="10" placeholder="Text">
</div>
<p class="changedClass">{{changeCounter}}</p>

My .ts

export class AppComponent  {
  name = 'Angular 6';
  text1 = '';
  changeCounter = 0;

  didModify() {
    this.changeCounter = this.changeCounter + 1;
    return this.changeCounter;
  }
}

Live Demo is here.

I saw in the past, it was $watch but I couldn't find an example in the official docs for Angular 5.

Upvotes: 0

Views: 4409

Answers (2)

Oscar Paz
Oscar Paz

Reputation: 18292

Just bind to the input event, which fires whenever the content of the input is modified in any way (including pasting, selecting and deleting, and so on):

<input (input)="didModify()" ... />

There you are.

https://stackblitz.com/edit/angular-ibuqqf

Upvotes: 4

user184994
user184994

Reputation: 18281

If it's bound using [(ngModel)], you can use (ngModelChange), like so:

<input maxlength="10" placeholder="Text" (ngModelChange)="didModify()" [(ngModel)]="text1">

This will call didModify each time the value changes, i.e. each keystroke

https://stackblitz.com/edit/angular-5zgbqm?file=src/app/app.component.html

Upvotes: 3

Related Questions