Lesson 12

Listening for Events and Binding to Properties

Using host bindings and host listeners to interact with the host component

PRO

Lesson Outline

Listening for Events and Binding to Properties

We're almost done with the theory, but there is one more important concept I want to cover before we jump into some more practical examples.

There are two important decorators that we can make use of in our components and directives called @HostListener and @HostBinding. A host listener will allow us to listen for, and respond to, events that occur on the host component. A host binding will allow us to bind values to properties on the host component - allowing us to modify styles, attributes, and more.

This concept is useful for both custom components and directives, but especially so for directives because their entire purpose is to modify the behaviour of whatever component they are attached to. They're like little parasites that cling to modify the behaviour of their host except... in a good way.

@HostBinding

We would use a host binding whenever we want to modify the host components properties in some way. Perhaps we would want to add a specific class to a component when a certain directive is attached to it, or maybe we want to modify that class or some other property based on some logic we perform.

In order to set up a host binding, we first need to import it:

import { Directive, HostBinding } from '@angular/core';
PRO

Thanks for checking out the preview of this lesson!

You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).