I've looked far and wide but I can't seem to find an answer. I've created a directive, which works fine, but I want to bind it to the host of a component dynamically.
Example:
@Directive({ selector: 'myDirective' })
@Component({ selector: 'myComponent',
template: 'some content goes here...'
})
export class MyComponent {
/* bind myDirective to host */
}
//when using myComponent, it should be
<myComponent></myComponent>
//not
<myComponent myDirective></myComponent>
I basically want to remove the need to either a) explicitly set myDirective
and b) wrap the template with an element just to use myDirective
@HostBinding and @HostListener are two decorators in Angular that can be really useful in custom directives. @HostBinding lets you set properties on the element or component that hosts the directive, and @HostListener lets you listen for events on the host element or component.
HostListenerlink Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs.
HostBindinglinkDecorator that marks a DOM property as a host-binding property and supplies configuration metadata. Angular automatically checks host property bindings during change detection, and if a binding changes it updates the host element of the directive.
As their names suggest, @HostListener() can listen to an event triggered on the host element and bind it to a method defined inside a directive class where as @HostBinding() decorator is used to set up a property binding on the host element and is applied to a directive property.
This is currently not supported.
See also https://github.com/angular/angular/issues/8785
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With