DEV Community

Manually Lazy load Components in Angular 8

Mayank Dubey on October 15, 2019

Angular is amazing! It is fast and smooth once loaded in the browser, but most often the start-up time suffers. Improving the start-up time for Ang...
Collapse
 
benifreitag profile image
Benjamin Freitag • Edited

Do you know how to get it to work with a Material Dialog instead of a viewcontainer, like this?

this.lazyLoader.load("lazy").then(res => {
      this.dialog.open(res.componentType)
    })
Enter fullscreen mode Exit fullscreen mode

I extended your sample at stackblitz.com/edit/lazy-angular-d... but also recieve Error: No component factory found for LazyComponent. Did you add it to @NgModule.entryComponents?

Collapse
 
binarysort profile image
Mayank Dubey

Hi,

Have you tried providing alternate componentFactoryResolver in material dialog config?

Collapse
 
benifreitag profile image
Benjamin Freitag • Edited

Thanks. Yes, I tried this but it still causes the same error in Angular 8. I updated the Stackblitz.

In Angular 9 this is fixed and there's no need to pass componentFactoryResolver 👏

Thread Thread
 
binarysort profile image
Mayank Dubey

I think it's related to this issue github.com/angular/angular/issues/...

Collapse
 
dileep3605 profile image
Dileep3605

am trying your solution everything was running but it's throwing error on this state

const compFactory = moduleRef.componentFactoryResolver.resolveComponentFactory(entryComponent);

Error: No component factory found for SiteedittoolModule. Did you add it to @NgModule.entryComponents?

if can anyone help me that will be great

Collapse
 
binarysort profile image
Mayank Dubey

Hi,

Can you share more code?

Collapse
 
fuhrermani profile image
fuhrermani

how to pass inputs and catch outputs from this component.

Collapse
 
binarysort profile image
Mayank Dubey • Edited

The createComponent() method returns a reference to the loaded component. Use that reference to interact with the component by assigning to its properties or calling its methods.

Add input and output in component:-

@Input()
data: string;

@Output()
event = new EventEmitter();

In the service just add:-

const compRef = container.createComponent(compFactory);

(compRef.instance as LazyComponent).data = 'this is data';
(compRef.instance as LazyComponent).event.subscribe(v => ... );

Read more about dynamic components here: angular.io/guide/dynamic-component...

Collapse
 
fasidongit profile image
Kader Mohideen Fasid

How do you write tests for dynamic import() in angular?

Collapse
 
binarysort profile image
Mayank Dubey
Collapse
 
cschwaderer profile image
Info Comment hidden by post author - thread only accessible via permalink
cschwaderer

This article is full of plagiarism. Many parts have been copied and slightly modified) from juristr.com/blog/2019/04/state-laz...

Some comments have been hidden by the post's author - find out more