Use of @HostBinding and @HostListener in Angular
@HostListener and @HostBinding in a directive provide a powerful tool for adding features to an existing component or an HTML element.
I have a use case of making a textbook with only numbers (our use case did not satisfy with input type number). There could be other use cases like adding color on hover, adding a feature to disable a button after a click and so many.
Let’s start adding the directive to a project
Generate directive via command line (ng CLI)
ng g d numeric-textbox
add host listener — in keydown event check if the typed key is numeric using regex.
this will do the work of restricting the user, but do not get feedback when typing an invalid key.
PS — did not ignore keys strokes like enter, escape, tab, arrow keys, delete and backspace.
Here comes @HostBinding which will set outline property.
Will need to clear the outline property set after a few milliseconds so on the next click it could be set again. setTimeout used for clearing the style after a few milliseconds.
outline — property do not impact document flow.
finally, it looks like this-
complete code
Instead of the style property, CSS class could be used. It will be topic for the other day.