0

From the Angular NgModule FAQ that talks about exporting declarables, it says that "If you don't export a declarable class, it stays private, visible only to other components declared in this NgModule", but this seems not correct.

Because from this live example of Angular Routes tutorial, I can still access HeroListComponent in all other components, like in AppComponent, in CrisisListComponent, etc.

But clearly in HeroesModule, I declared HeroListComponent, but I did not export it. It seems that even if I don't export the declarables (pipes, components, directives), I can still access these declarables from outside of the module that declares them. So why is this happening?

Here's how I access HeroListComponent from outside the HeroesModule:
(this file is app-routing.module.ts)

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { ComposeMessageComponent }  from './compose-message.component';
import { PageNotFoundComponent }    from './not-found.component';

import { CanDeactivateGuard }       from './can-deactivate-guard.service';
import { AuthGuard }                from './auth-guard.service';
import { SelectivePreloadingStrategy } from './selective-preloading-strategy';
import { HeroListComponent } from './heroes/hero-list.component';

const appRoutes: Routes = [
  {
    path: 'compose',
    component: ComposeMessageComponent,
    outlet: 'popup'
  },
  {
    path: 'test',
    component: HeroListComponent
  },
  {
    path: 'admin',
    loadChildren: 'app/admin/admin.module#AdminModule',
    canLoad: [AuthGuard]
  },
  {
    path: 'crisis-center',
    loadChildren: 'app/crisis-center/crisis-center.module#CrisisCenterModule',
    data: { preload: true }
  },
  { path: '',   redirectTo: '/superheroes', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(
      appRoutes,
      {
        // enableTracing: true, // <-- debugging purposes only
        preloadingStrategy: SelectivePreloadingStrategy,

      }
    )
  ],
  exports: [
    RouterModule
  ],
  providers: [
    CanDeactivateGuard,
    SelectivePreloadingStrategy
  ]
})
export class AppRoutingModule { }

No error is seen when navigating to the path "test"(http://localhost:4200/test) and everything works fine.

Bohao LI
  • 2,123
  • 2
  • 18
  • 24

1 Answers1

0

Export declarable classes that components in other NgModules are able to reference in their templates.

Export defines a scope for template rendering and router uses ComponentFactory to initialize component. As far as all the components referenced by HeroListComponent are declared/imported by AppRoutingModule, this is gonna work.