Search code examples
angular6angular7

lazy load module in matDialog


I have a component which is part of a lazy load module.

Is there a way to matDialog.open() and lazy load the module and show the component?

export class testComponent implements OnInit {
  constructor(
    public matDialog: MatDialog,
    private moduleLoader: NgModuleFactoryLoader
  ) {}
  ngOnInit() {}

  openModal() {
    this.moduleLoader
      .load("./modules/test-modal/test-modal.module#TestModalModule")
      .then((module: NgModuleFactory<any>) => {
        this.matDialog.open(/*insert component and load the module*/);
      });
  }
}

Solution

  • I found an example to lazy load module with component in mat-dialog.

    Please see refer to:

    Just in case the link is no longer available, i'd included a brief step and example to do it

    1. Create a lazy load module

    2. Create entry component(empty component) to launch your modal component

    @Component({
    template: ''
    })
    export class DialogEntryComponent {
        constructor(public dialog: MatDialog, private router: Router,
        private route: ActivatedRoute) {
        this.openDialog();
        }
        openDialog(): void {
        const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
            width: '250px'
        });
        dialogRef.afterClosed().subscribe(result => {
            this.router.navigate(['../'], { relativeTo: this.route });
        });
        }
    }
    

    3. Create a route for the lazy load module

    const routes: any = [
        {
        path: "",
        component: modalComponent(actual component with content)
        }
    ];
    @NgModule({
        imports: [RouterModule.forChild(routes)],
        exports: [RouterModule],
        providers: [DataResolver]
    })
    export class DialogEntryRoutingModule {}
    

    4. At parent router module, include path to lazy load DialogEntryModule

    RouterModule.forRoot([
        {
          path: 'home',
          component: ParentComponent,
          children: [
            {
              path: 'dialog',
              loadChildren:
                  "../example/entry-dialog.module#DialogEntryModule"
            }
          ]
        },
        { path: '**', redirectTo: 'home' }
      ])
    

    5. in ParentComponent open the modal by directing to the DialogEntryModule

    <button mat-raised-button routerLink="dialog">Pick one</button>