I\'m trying to detect when the value of an input changed in a directive. I have the following directive:
As of Angular 9+ I can verify that the snippet below is the correct solution. It's best to avoid ngOnChanges
whenever possible for several reasons and use the correct host listener event instead. The below example will get the current input value on keyup
. You can easily customize this code snippet for whatever you need on an input directive.
@Directive({
selector: '[appMyDirective]',
})
export class MyDirective {
// Add whatever event you want to track here
@HostListener('keyup', ['$event']) public onKeyup(event: KeyboardEvent): void {
const value = (event.target as HTMLInputElement).value;
console.log(value);
}
}