21

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?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Yona Appletree
  • 8,801
  • 6
  • 35
  • 52

2 Answers2

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

This can now be achieved with hostDirectives in Angular v15+

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

Details in the Angular docs

Drenai
  • 11,315
  • 9
  • 48
  • 82