3

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.

Simon
  • 33
  • 3
  • 1
    i removed the ComponentsModule, and merge the declaration of the component and the highlight directive and it work fine with me. – Raed Khalaf Jul 11 '17 at 13:55

1 Answers1

1

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • hi Gunter Zochbauer, can you help me with this question,https://stackoverflow.com/questions/45005949/angular-guards-unclear-statement-in-the-docs – Raed Khalaf Jul 11 '17 at 14:03
  • i asked it yesterday, but no one answer it! – Raed Khalaf Jul 11 '17 at 14:03
  • Thanks Günter! You are right. When I add another module `DirectivesModule` and add the `HighlightDirective` to it's `imports: []` it works. [Plunkr for reference](https://embed.plnkr.co/3bOpnWGV40fJlY9rndWw/). I guess what confused me is that Angular does not report that it did not find the attribute directive as it does with missing components when they are used in the template. [Plunkr for reference](https://embed.plnkr.co/3bOpnWGV40fJlY9rndWw/) – Simon Jul 11 '17 at 14:08
  • I don't know about that stuff. I'm not using TS Angular myself (only in Plunker for SO answers). – Günter Zöchbauer Jul 11 '17 at 14:13