Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate and apply directives programmatically?

I know that in ng2 we have ComponentFactoryResolver that can resolve factories that we can apply to a ViewContainerRef.

But, is there something similar for directives? a way to instantiate them and apply them to the projected content from a component?

like image 236
lqbweb Avatar asked Sep 18 '16 23:09

lqbweb


2 Answers

No, directives can't be added or removed dynamically. They are only applied to HTML statically added to component templates.

What you could do is to enable/disable the directive by passing a parameter (@Input()) to the directive to notify it to do something or not.

like image 127
Günter Zöchbauer Avatar answered Oct 14 '22 01:10

Günter Zöchbauer


It's not impossible. It's just ugly and error prone. Basic thing to remember is that a directive is first a class. If you can manually get your hands on the stuff the constructor needs, you can simply do something like:

const highlight = new HighlightDirective(...);

Be prepared for possibly running into unexpected behaviors as you will escape Angular's hands.

Read my full answer here on dynamically adding directives.

like image 25
Shy Agam Avatar answered Oct 14 '22 02:10

Shy Agam