At the time of its creation, Angular apps load all modules immediately irrespective of their utility and usage in the app. Enter lazy loading. To reduce the number of components the app needs to load and save on resources such as processor power and network bandwidth, we implement the lazy loading pattern in the app. Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.
Lazy loading of single components has not been possible so far. However, with Angular Ivy (or just Ivy), more abilities are now possible.
Locality in Ivy
Modules are the main building blocks of Angular. These contain several components, directives, pipes, and services. In layman’s terms, today’s application cannot exist without these modules.
Ivy introduces the concept of ‘Locality’ in which a component can exist without a module. With Locality, all the metadata is local to that particular component.
A real-world application of Lazy Loading of Component
Create a new application using Angular CLI. Our app.component.ts file will look like this:
import { Component } from '@angular/core'; @Component({ selector: 'app-component', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'my-app'; }
ng g greet — flat — skip-import
In the above command, skip-import will not import the component in the current module. We will load this component inside the module using lazy load.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'greet', templateUrl: './greet.component.html', styleUrls: ['./greet.component.scss'] }) export class GreetComponent implements OnInit { constructor() { } ngOnInit() { } }
We see that the greet component is created and we will pass data to this component,
@Input() message: string; @Output() sendEventEmmiter = new EventEmitter()
For now, this is sufficient for the greet component. We will now lazy load the greet component in the app.component. To do this, we have to inject
viewContainerRef and ComponentFactoryResolver constructor(private vcrf: ViewContainerRef, private cfr: ComponentFactoryResolver) { }
What is viewContainerRef? – This is a container in which one or more views can be attached
What is ComponentFactoryResolver? – This is a simple registry that maps Components to generated ComponentFactory classes.
These classes can be used to create instances of components. Use these to obtain the factory for a given component type, then use the factory’s create() method to create a component of that type.
Create the method
Now create the method to lazy load the component in app.component
loadComponent() { this.vcrf.clear(); import('./greet/greet.component').then(({ GreetComponent }) => { let greetComp = this.vcrf.createComponent( this.cfr.resolveComponentFactory(GreetComponent) ); }); }
Here we are using promises of JavaScript. These allow us to load the component only if the promise returns successfully. We are also using viewContaierRef, and it’s method createComponent() in which we are passing componentFactoryResolver. These should be able to create the component and host inside that particular viewContainerRef.
If you see, we still are not passing any value to the greetComponent. In the above code, you will notice that we have a variable called greetComp. This variable contains a reference to a lazy loaded component that we can use to pass data.
greetComp.instance.message = 'I am from app.component'; greetComp.instance.sendEventEmmiter.subscribe(data => { console.log(data); });
When we combine all the above code so then our loadComponent() method will look like this,
loadComponent() { this.greetViewchildRef.clear(); import('./greet/greet.component').then(({ GreetComponent }) => { let greetComp = this.greetViewchildRef.createComponent( this.cfr.resolveComponentFactory(GreetComponent) ); greetComp.instance.message = 'I am from app.component'; greetComp.instance.sendEventEmmiter.subscribe(data => { console.log(data); }); }); }
Displaying the result
To display the result, we have to load the greetComponent in the app.component.html file.
<div> <ng-template #greetComp> </ng-template> </div> <button (click)="loadComponent()">Load component</button>
Here we use the ng-template to load the greetComponent. We also need to add viewChild() to show the component data.
@ViewChild('greetComp', {read: ViewContainerRef}) private greetViewchildRef: ViewContainerRef
Note that if we want to use any module, then we need to add the decorator to the component itself, and then import the module within it.
@NgModule({ declarations: [GreetComponent], imports: [FormsModule] }) class GreetComponentModule {}
Conclusion
We can create the component using a normal flow. However, what if we want to use the created component only for a specific action? If we use the usual way, we can reduce our application load by using a lazy load component.
To view the full application click here: https://stackblitz.com/edit/lazy-load-component.If you liked this post, here are a few more that may interest you:
“Synerzip team is very responsive & quick to adopt new technologies. Team naturally follows best practices, does peer reviews and delivers quality output, thus exceeding client expectations.”
“Synerzip’s agile processes & daily scrums were very valuable, made communication & time zone issues work out successfully.”
“Synerzip’s flexible and responsible team grew to be an extension to the StepOne team. Typical concerns of time zone issues did not exist with Synerzip team.”
“Synerzip worked in perfect textbook Agile fashion – releasing working demos every two weeks. Though aggressive schedules, Synerzip was able to deliver a working product in 90 days, which helped Zimbra stand by their commitment to their customers.”
“Outstanding product delivery and exceptional project management, comes from DNA of Synerzip.”
“Studer product has practically taken a 180% turn from what it was, before Synerzip came in. Synerzip cost is very reasonable as compared to the work they do.”
“Synerzip makes the timezone differences work FOR the customer, enabling a positive experience for us. ‘Seeing is believing’, so we decided to give it a shot and the project was very successful.”
“The Synerzip team seamlessly integrates with our team. We started seeing results within the first sprint. And due to the team’s responsiveness, we were able to get our product to the sales cycle within 7 months.”
“Product management team from Synerzip is exceptional and has a clear understanding of Studer’s needs. Synerzip team gives consistent performance and never misses a deadline.”
“Synerzip is different because of the quality of their leadership, efficient team and clearly set methodologies. Studer gets high level of confidence from Synerzip along with significant cost advantage of almost 50%”
“Synerzip’s hiring approach and practices are worth applauding. Working with Synerzip is like
“What you see is what you get”.”
“Synerzip has dedicated experts for every area. Synerzip helped Tangoe save a lot of cost, still giving a very high quality product.”
“Synerzip gives tremendous cost advantage in terms of hiring and growing the team to be productive verses a readymade team. Synerzip is one company that delivers “co –development” to the core!”
“Synerzip is a great company to work with. Good leadership and a warm, welcoming attitude of the team are additional plus points.”
“Our relationship with Synerzip is very collaborative, and they are our true partners as our values match with theirs.”
“Synerzip has proven to be a great software product co-development partner. It is a leader because of its great culture, its history, and its employee retention policies. ExamSoft’s clients are happy with the product, and that’s how ExamSoft measures that all is going well.”
“They possess a great technical acumen with a burning desire to solve problems. The team always takes the initiative and ownership in all the processes they follow. Synerzip has played a vital role in our scaling up and was a perfect partner in cost, efficiency, and schedules.”
“As we are a startup, things change on a weekly basis, but Synerzip team has been flexible in adapting the same”
“Synerzip team has been very proactive in building the best quality software, bringing in best practices, and cutting edge innovation for our company.”
“We’ve been working for more than six years with Synerzip and its one of the better, if not the best, experience I’ve had working with an outsourcing company.”
“My experience with Synerzip is that they have the talent. You throw a problem at them, and someone from that team helps to solve the issue.”
“The breadth and depth of technical abilities that Synerzip brings on the table and the UX work done by them for this project exceeded my expectations!”
“Synerzip UX designers very closely represent their counterparts in the US in terms of their practice, how they tackle problems, and how they evangelize the value of UX.”
“Synerzip team understood the requirements well and documented them to make sure they understood them rightly.”
“Synerzip is definitely not a typical offshore company. Synerzip team is incredibly communicative, agile, and delivers on its commitments.”
“Working with Synerzip helped us accelerate our roadmap in ways we never thought possible!”
“While working with Synerzip, I get a feeling of working with a huge community of resources, who can jump in with the skills as needed.”