Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind custom directive to host

Tags:

angular

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

like image 977
Jacob Roberts Avatar asked May 29 '16 18:05

Jacob Roberts


People also ask

What are HostBinding () and HostListener () in Angular?

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

What is the use of @HostListener?

HostListenerlink Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs.

What is the HostBinding?

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.

Which directive is used for event binding methods in custom 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.


1 Answers

This is currently not supported.

See also https://github.com/angular/angular/issues/8785

like image 124
Günter Zöchbauer Avatar answered Oct 02 '22 04:10

Günter Zöchbauer