6
votes

I am a bit new to angular 4. I am trying to get change event from an input field inside a directive. Currently i am working with @HostListener

@HostListener('keyup', ['$event'])
  inputChanged(event) {}

This is working correctly but this event is fired after some delay from releasing key and user can enter wrong input and is able to see that too. In my implementation i have removed the invalid input but it doesn't give a good exposure to user. Only thing i want is to get change event right the moment change happen in input field (character / string enter or remove both ). Current HTML looks like this

<input type='text' class="form-control" placeHolder='hh:mm:ss' time-input [(ngModel)]="params.time" name="time"/>

PS. time-input is the name of directive and in directive i am trying to get the event change and i don't want to move any implementation to controller or component.

1
do you want to get native DOM event or event from ngModel directive? - Max Koretskyi
i don't have any restriction for using any event type.i was using native DOM event at first but there was a problem in that but @gunter's answer worked and it is according requirements now - Ali Khan
you need input event for the DOM native element. Gunter's solution will only work if there's ngModel directive on the input. So your time-input will only work alongside ngModel, it can't be used as a standalone directive - Max Koretskyi
ok got it now i have two way i can cake ngModel necessory for that directive second update event (ngModelChange) to input event. Thanks for guidance. i will do it.:) - Ali Khan

1 Answers

9
votes

Use

@HostListener('ngModelChange', ['$event'])