Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Route to a Component in a different Module?

Tags:

angular

CharacterComponent is in a different Module from MenuModule. I don't know the right way to route to a Component in a different Module. I want to be able to switch the target of <router-outlet></router-outlet> to Components in different Modules. This is as far as I got and it doesn't work.

menu.module.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { HttpClientModule } from '@angular/common/http';
    import { RouterModule } from '@angular/router';

    import { MenuComponent } from './menu.component';
    import { CharacterComponent } from '../character/character.component';

    @NgModule({
      declarations: [
        MenuComponent,
        CharacterComponent
      ],
      imports: [
        BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
        HttpClientModule,
        FormsModule,
        RouterModule.forRoot([
          { path: '', component: CharacterComponent, pathMatch: 'full' }
       ])
      ],
      providers: [],
      bootstrap: [MenuComponent]
    })
    export class MenuModule { }
like image 278
Mark Avatar asked Oct 22 '25 05:10

Mark


2 Answers

This is a basic example, but make sure to import AppRoutingModule into AppModule (Not shown) and LoginRoutingModule to LoginModule (Not shown). Otherwise it wont work. Also notice the forRoot and forChild methods in each routing module. In this case if the user goes to localhost:4200 it will redirect to localhost:4200/start and load the LoginComponent. Let me know if you have any questions.

** AppRoutingModule **

const routes: Routes = [
  {
    path: '',
    redirectTo: 'start',
    pathMatch: 'full'
  },
  {
    path: 'start',
    loadChildren: 'app/modules/routes/login/login.module#LoginModule'
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes)
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule {}

** LoginRoutingModule **

const routes: Routes = [
  {
    path: '',
    component: LoginComponent,
    redirectTo: 'login'
  }
]

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [
    RouterModule
  ],
  providers: []
})
export class LoginRoutingModule {}
like image 98
Dan Avatar answered Oct 24 '25 17:10

Dan


Would suggest move the 'CharacterComponent' to shared module and export it. In menu module, you can import sharedmodule.

In Menu Module, you can create a component that will contain CharacterComponent as child component. Now you can create route for the newly created component.

like image 37
Suresh Kumar Ariya Avatar answered Oct 24 '25 19:10

Suresh Kumar Ariya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!