Detect when input value changed in directive

后端 未结 4 1800
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 17:48

I\'m trying to detect when the value of an input changed in a directive. I have the following directive:

         


        
4条回答
  •  清酒与你
    2021-02-03 18:27

    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);
        }
      }

提交回复
热议问题