Angular how to import RouterModule for lazy loading Component

Viewed 31

I have a lazy loading component for my Angular 13 project

  async loadModals() {
    this.viewContainerRef.clear();
    const { McComponent } = await import('./components/modal/mc.component');
    this.viewContainerRef.createComponent(this.componentFactoryResolver.resolveComponentFactory(McComponent));
  }

But can not figure out how to import RouterModule in it in order to have working links

        <a [routerLink]="['/mcu']" class="upgrade-link">
          {{ upgradeLinkLable | translate }}
        </a>
1 Answers

OK, I figure it out.

In most examples of lazy loading components, it is shown to add this NgModule decorator in the components file.

For example

@NgModule({
  declarations: [GreetComponent],
  imports: [FormsModule]
})
class PlanetComponentModule {}

I did not find more specific info and I was a bit confused. So here is the key.

This is my example of a modal component, but let me first mention the key points.

  1. You add @NgModule at the bottom of the file!

  2. You add all modules that you would like to use in the imports section in NgModule. for declarations section you should add the main component and all other components that it uses (in my case MoveFilesComponent). That way RouterModule will be available for all of them.

  3. Name of the module has no relation with the component so you can name it whatever you want, but anyway be more specific

  4. If you need some service, not part of any module or just need only that service you can add it in @Component providers slot (I did that for MoveFilesService).

Hope that helps. Cheers!

import { Component, NgModule, OnDestroy, OnInit } from '@angular/core';
import { RouterModule } from '@angular/router';
import { MoveFilesService } from './services/move-files.service';
import { MoveFilesComponent } from './modals/move-files/move-files.component';



@Component({
  selector: 'nx-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.scss'],
  providers: [MoveFilesService],
})
export class ModalComponent implements OnInit, OnDestroy {
 ...
}

@NgModule({
  declarations: [
    ModalComponent,
    MoveFilesComponent,
  ],
  imports: [RouterModule],
})
class ModalModule {} /* Whatever you name it */
Related