Angular 6 directive is not initialized when placed in lazy loaded module's component
Asked Answered
C

2

7

Very new to Angular 6.

I have declared a directive in AppModule and in the appComponent template if I apply that directive it works, In the app component there is a router outlet in which a lazy loaded module gets loaded at very beginning.

Now if I want to apply the directive in any component template of the lazyloaded module, the directive is not being initialized. The directive is an attribute directive and I have declared it properly and used too because inside app component it's working fine.

Not getting any clue, please help.

Cutie answered 27/6, 2018 at 17:39 Comment(3)
A directive must be declared, or imported in order to be used by a module. Since it's declared in AppModule, it's only available in that module. You need to declare it and export it in a shared module, and import that shared module in all modules that need to use that directive. angular.io/guide/sharing-ngmodulesDaniels
You have to export your directive from the module to be used by external components.Add this to your module file where you have declared it exports : [MyDirective]Seraphina
OK, now the issue is I have declared this at AppModule and export too. I thought if anything declared in app module should be available to all modules. As I have declared it in AppModule so not declared in any shared module and so did not import anything extra.Cutie
S
18

I see there is an issue with your design. Instead of having your directive in the AppModule, create a SharedModule and then implement the directive in there. Import SharedModule everywhere else in your app. This way you can access your directive from external components (from other modules).

Make sure you declare and export it inside SharedModule

I thought if anything declared in app module should be available to all modules

No this is not correct, Child modules does not know what you have inside the AppModule. ChildModule's are just another independent modules like AppModule. You could have simply exposed AppModule to ChildModule, but that might cause the circular dependency. That is the reason you have to make use of SharedModule

Seraphina answered 27/6, 2018 at 18:14 Comment(0)
R
0

If we create directives in the feature module/shared module make sure that we need to have them put in the declaration section and export section. import this feature/shared module where it is used.

Rebellious answered 27/8, 2019 at 13:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.