Use of @HostBinding and @HostListener in Angular

Prateek Singh
2 min readDec 24, 2021

--

@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.

hostListener code snippet

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.

hostBinding snippet

finally, it looks like this-

finally look when host listener and host binding added

complete code

Instead of the style property, CSS class could be used. It will be topic for the other day.

--

--

Prateek Singh
Prateek Singh

Written by Prateek Singh

I am a full-stack developer. Working on angular, .net, and azure. I like to read about CSS, web design, and authentication.

No responses yet