Search code examples
angularroutesangular-routerangular-routerlink

Angular routing from one component to another


I have one component called main that has main.routing.ts as defined here:

@NgModule({
  imports: [
    RouterModule.forRoot([
      { path: 'main',
        component: MainComponent,
        canActivate: [AuthGuard],
        children: [{ path: '', component: AccountMainComponent },
      { path: 'financial-accounts', component: FinancialAccountsComponent },
      { path: 'system-config', component: ConfigSysComponent },
      { path: 'conciliacao', component: ConciliacaoContabilComponent },
      { path: 'report', component: ReportComponent },
      ]}
    ])
  ]
 })
 export class MainRouting { }

And I'm have another content-toolbar component where I wanna create a link to main component. content-toolbar imports router at content-toolbar.module.ts and at content-toolbar.component.ts. I have at content-toolbar.component.html this piece of code:

<span>
    <a routerLink="/main">
      <img src="/assets/icons/logo_white.svg" class="logo">
    </a>
</span>

But this code doesn't turn this image into a link to the other component. How should I reference main component to be router(ed) to from content-toolbar?


Solution

  • Ill take my guess and state the following:

    Most likely you declare ContentToolbarComponent in a module that looks like this

    @NgModule({
    imports: [..., MainRoutingModule,...],
    declarations: [..., ContentToolbarComponent, ...]
    })
    export class FooModule {}
    

    The problem is that you probably dont import the RouterModule, which exports the RouterLinkDirective, into FooModule. Thats why angular is not generating anchor elements with hyperlinks.

    The solution would be to add the RouterModule into the exports of your MainRoutingModule as follows:

    @NgModule({
      imports: [
        RouterModule.forRoot([
          { path: 'main',
            component: MainComponent,
            canActivate: [AuthGuard],
            children: [{ path: '', component: AccountMainComponent },
          { path: 'financial-accounts', component: FinancialAccountsComponent },
          { path: 'system-config', component: ConfigSysComponent },
          { path: 'conciliacao', component: ConciliacaoContabilComponent },
          { path: 'report', component: ReportComponent },
          ]}
        ])
      ],
      exports: [RouterModule]
     })
     export class MainRouting { }
    

    The important thing is that, the module that declares the toolbar component has to import the RouterModule directly or through the exports of another imported module, so that the toolbar component can use the directive.