Use directive in host of another Directive
Asked Answered
P

2

22

I want to add a directive to an element from another directive by using the host property, but there doesn't seem to be a way to reference the other directive.

@Directive({
    selector: '[one]',
    host: { '[two]': '"some-value"' }
    // How can I reference DirectiveTwo here?
})
export class DirectiveOne { }

@Directive({
    selector: '[two]'
})
export class DirectiveTwo { }

When doing this, I get the standard "Can't bind to 'two' since it isn't a known native property" error.

What is the correct way of referencing and using one directive from another?

Prog answered 10/5, 2016 at 20:12 Comment(0)
F
3

This can now be achieved with hostDirectives in Angular v15+

@Directive({
  selector: '...',
  hostDirectives: [Tooltip, Menu],
})
export class MenuWithTooltip { }

Details in the Angular docs

Flavorous answered 22/3, 2023 at 22:43 Comment(0)
G
16

Directives are instantiated by Angular for selectors matching statically added HTML (element, id, attribute, class, ...) only.
There is no way to instantiate directives using the host parameter of the @Component() or @Directive() decorator. There is also no way to create directives dynamically using ViewContainerRef.createComponent() (former DynamicComponentLoader)

Getting a reference to another directive that was instantiated by Angular because of a statically added HTML on the same element is supported though.

Goodman answered 11/5, 2016 at 6:21 Comment(2)
If that is so, what is the best practice for having one Directive extend or use the functionality of others? This seems like a pretty significant limitation.Prog
I think this is a topic for a bigger update github.com/angular/angular/issues/11606Vasodilator
F
3

This can now be achieved with hostDirectives in Angular v15+

@Directive({
  selector: '...',
  hostDirectives: [Tooltip, Menu],
})
export class MenuWithTooltip { }

Details in the Angular docs

Flavorous answered 22/3, 2023 at 22:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.