Listening for Events and Binding to Properties
Using host bindings and host listeners to interact with the host component
PROModule Outline
- Source Code & Resources PRO
- Lesson 1: Introduction PUBLIC
- Lesson 2: The Role of Components and Directives PUBLIC
- Lesson 3: When to Use Custom Components & Directives PRO
- Lesson 4: Building a Simple Component PRO
- Lesson 5: Building a Simple Directive PRO
- Lesson 6: Setting up Components and Directives PRO
- Lesson 7: Using @Input and @Output PRO
- Lesson 8: Using ElementRef and Renderer PRO
- Lesson 9: Understanding Content Projection PRO
- Lesson 10: Understanding @ViewChild and @ContentChild PRO
- Lesson 11: Building a Complex Component PRO
- Lesson 12: Listening for Events and Binding to Properties PRO
- Lesson 13: Building a Skeleton Card Component PRO
- Lesson 14: Creating an Autogrow Directive for a Textarea PRO
- Lesson 15: Handling Error Messages with a Custom Component PRO
- Lesson 16: Building a Parallax Header Directive PRO
- Lesson 17: High Performance Accordion Component PRO
- Lesson 18: Conclusion 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';
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).