Dynamically mount angular 2 directive

Context

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

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

The myDirective directive simply executes some logic in the hook ngOnInit and decorates its own ElementRef element (in this case, the button), adding attributes is nothing complicated.

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

Problem

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

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

+5
source share
2 answers

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

+2
source

You do not add or remove directives dynamically, but if you want to add a tooltip, you need to insert a div into your component template, which activates it depending on the state of the variable

 <div [hidden]="tooltipnotshown" class="tooltip"> blah blah or whatever ... </div> 
+2
source

Source: https://habr.com/ru/post/1269800/


All Articles