nicker
nicker

Reputation: 487

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*/);
      });
  }
}

Upvotes: 5

Views: 6815

Answers (2)

Tetsuto Yabuki
Tetsuto Yabuki

Reputation: 96

Another alternative is to stick the mat dialog component in another module that has a route, assuming it isn't used by any other module.

For example, if you have app.module and a projects.module, and you have a mat dialog that displays project details, you could include the project details dialog component inside of projects.module instead of creating a separate module for it. The dialog code will load when the user navigates to the projects view.

@nicker's answer runs into issues when you close the dialog. This reloads the parent component and in some cases, you don't want the parent component view to be refreshed.

Upvotes: 1

nicker
nicker

Reputation: 487

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>

Upvotes: 4

Related Questions