eddyuk
eddyuk

Reputation: 4190

change event is not firing

I have a scenario where the textbox might change but not resulting from user input and I need to detect this change. Input defined as following:

<input type="text" (change)="onChange($event)" >

And in .ts I have the onChange method:

onChange(event:any){
  // something todo here
}

From what I understand, that should work in Angular 9, but the event is not firing. What am I missing?

Upvotes: 2

Views: 12250

Answers (4)

Rob Monhemius
Rob Monhemius

Reputation: 5144

the issue

Changing the value programatically does not trigger the change event.

emit your own event

You can create your own Event using the Event API. You will need access to the node you are binding the Event to ( you can use ViewChild)

See a live example in this stackblitz demo.

app.component.ts

import { Component, ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  value = '';
  @ViewChild('input') input;
  onChange(event:any){
    alert('change event triggered');

  }
  changeValue() {
    this.value = 'Value set';
    // also trigger an event on the input.
    let event = new Event('change');
    this.input.nativeElement.dispatchEvent(event);
  }
}

app.component.html

<input #input type="text" (change)="onChange($event)" [value]='value'>
<button (click)='changeValue()'>Change</button>;

or

Or you can do it another way and run the code in the onChange method directly after programatically changing the value. Note that you may need to refactor your code in order not to rely on an emitted $event.

Upvotes: 0

Akinbode A.
Akinbode A.

Reputation: 66

<input type="text" (keyup)="onChange($event)" >

Use keyUp event for input element.

Upvotes: 1

Rohit Tagadiya
Rohit Tagadiya

Reputation: 3720

You can try these ways ..

In angular you can do like this: <input type="text" (keyup)="myFunction(this)"> you can use (keyup)="yourFunction()" event.

CASE 1

You can use onkeyup event

function myFunction(e) {
  console.clear();
  console.log(e.value);
}
<form>
   <label for="fname">First name:</label><br>
   <input type="text" id="fname" name="fname" onkeyup="myFunction(this)"><br>
</form>

CASE 2

You can use oninput event

function myFunction(e) {
  console.clear();
  console.log(e.value);
}
<form>
   <label for="fname">First name:</label><br>
   <input type="text" id="fname" name="fname" oninput="myFunction(this)"><br>
</form>

Upvotes: 2

Emad Abdou
Emad Abdou

Reputation: 287

Try to use input event as

<input type="text" (input)="onChange($event)" >

and it will work with you

Upvotes: 0

Related Questions