@HostBinding
: This decorator binds a class property to a property of the host element.@HostListener
: This decorator binds a class method to an event of the host element.import { Component, HostListener, HostBinding } from '@angular/core';
@Component({
selector: 'app-root',
template: `<p>This is nice text<p>`,
})
export class AppComponent {
@HostBinding('style.color') color;
@HostListener('click')
onclick() {
this.color = 'blue';
}
}
In the above example the following occurs:
color
property in our AppComponent
class is bound to the style.color
property on the component. So whenever the color
property is updated so will the style.color
property of our component@Directive
:Although it can be used on component these decorators are often used in a attribute directives. When used in an @Directive
the host changes the element on which the directive is placed. For example take a look at this component template:
<p p_Dir>some paragraph</p>
Here p_Dir is a directive on the <p>
element. When @HostBinding
or @HostListener
is used within the directive class the host will now refer to the <p>
.