Search code examples
angularangular-routingangular-directiveangular-componentsangular-component-router

Angular 4: Custom Attribute Directive within <router-outlet> not being executed


I am currently trying to create a custom attribute directive for my Angular 4 (v 4.2.6) application with component based routing. I have followed the official Angular guide on how to create such an attribute directive.

Everything works fine, when the myHighlight directive is put on the root component. Unfortunately it does not work (the attribute directive is not executing) when used in combination with @angular/router inside a component being inserted in the router-outlet.

To isolate the problem from my application, I have created a Plunkr showing the issue.

On this Plunkr you can see a custom attribute directive called myHighlight (highlight.directive.ts). This directive is used in the root component (app.ts).

Then I added two components that are used with the router for component based routing: OneComponent (one.component.ts) and TwoComponent (two.component.ts) being bound to /one respectively /two. Within those two components the myHighlight directive is also used, but sadly does not render / execute correctly and only the text of the HTML element (p) it is bound to is displayed.

If anyone could give me a pointer to what I am doing wrong or what needs to be changed I would be very grateful.


Solution

  • declarations: [] from AppModule are only available to components in ComponentsModule. If you want to reuse components or directives in different modules, create a featuremodule and add this featuremodule to imports: [] of every module where you want to use them.