How to instantiate and apply directives programmatically?

lqbweb picture lqbweb · Sep 19, 2016 · Viewed 7.5k times · Source

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?

Answer

Günter Zöchbauer picture Günter Zöchbauer · Sep 19, 2016

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.