5

Context

I have a simple directive that add some attributes to a given HTML element based on received attributes.

<button class="btn btn-blue x-large" [myDirective]="{ some_json_data: true }">
    Unfold
</button>

The myDirective directive just does some logic in the ngOnInit hook and decorates the ElementRef native element (in this case the button) adding attributes, nothing complicated.

ngOnInit(): void {
  const el: Element = this.element.nativeElement;
  this.decorate(el, this.myDirective);
}

Problem

Based on a given logic (in myDirective decoration) I want to add a tooltip (which is another directive) to the element referenced by ElementRef at myDirective.

How do I mount a directive manually and how do I add it to an element (ViewContainerRef)?

0mpurdy
  • 3,198
  • 1
  • 19
  • 28
Miguel Lattuada
  • 5,327
  • 4
  • 31
  • 44
  • 3
    you can't add directives to the html after it was compiled, read [Here is what you need to know about dynamic components in Angular](https://hackernoon.com/here-is-what-you-need-to-know-about-dynamic-components-in-angular-ac1e96167f9e) – Max Koretskyi Jul 13 '17 at 15:49

2 Answers2

2

Adding or removing directives dynamically is not supported. Only components can be added and removed dynamically (only dynamically added components can be removed dynamically).

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Bounty asks for credible sources: [this GitHub issue](https://github.com/angular/angular/issues/8785) I think is relevant – 0mpurdy Jul 28 '17 at 00:57
2

You do not add or remove directives dynamically, but if you want to add a tooltip you have to insert a div in your component template that activates it depending on a variable status

<div [hidden]="tooltipnotshown"
     class="tooltip">
 blah blah or whatever ...
</div>
sancelot
  • 1,905
  • 12
  • 31