简体   繁体   中英

How to use routing with module instead of component in Angular 10+

I successfully used component in routing but when i am using module instead of component in angular 10 i am getting a white screen.

I would be really thankful for any kind of help.

this is what i've been trying: app-routing.module.ts

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

import { DashboardModule } from './components/dashboard/dashboard.module';

import { DashboardComponent } from './components/dashboard/dashboard.component';

const routes: Routes = [
    { path: '', loadChildren: () => DashboardModule }
];

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

Dashboard module:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { DashboardComponent } from './dashboard.component';


@NgModule({
  declarations: [
    DashboardComponent
  ],
  imports: [
    CommonModule
  ]
})
export class DashboardModule { }

Dashboard Component:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  constructor() { 
    alert('asdf');  
  }

  ngOnInit(): void {
  }

}

Thanks

Lazy loaded feature modules have to have their child routes declared separately. For example:

    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { DashboardComponent } from './dashboard.component';

    const routes: Routes = [
      {
        path: '',
        component: DashboardComponent,
      },
    ];
    
    @NgModule({
      imports: [RouterModule.forChild(routes)],
      exports: [RouterModule]
    })
    export class DashboardRoutingModule { }

Also make sure to always load lazy modules like Emilien said before :)

loadChildren: () => import('./components/dashboard/dashboard.module').then(m => m.DashboardModule)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM