Angular 9 - Lazy load components using ivy compiler

Recently Angular 9 was officially released with new ivy compiler. Lets dive into how to lazy load your component using angular 9 latest update on ivy compiler for better perfomance.

Angular 9 - Lazy load components using ivy compiler

We don't need to add this components in entryComponents, angular 9 finds the lazy loaded components by itself. Interesting?

Get started with Lazy Load

import { Component } from '@angular/core';

  template: `Hello works!`
export class HelloComponent { }

We have created simple component, now lets try to lazy load on a button click event.

import { HelloComponent } from './hello/hello.component';

  template: `
    <button (click)="loadHello()">Load HelloComponent</button>
    <ng-container *ngIf="helloLazyComponent">
       <ng-template [ngComponentOutlet]="helloLazyComponent | async"></ng-template>
export class AppComponent {
  helloLazyComponent: Promise<Type<HelloComponent>>;

  loadHello() {
    if (!this.helloLazyComponent) {
      this.hello = import(`./hello/hello.component`)
                       .then(({ HelloComponent }) => HelloComponent);

We have imported HelloComponent into AppComponent and we have loadHello event which is fired when the user click on the button - 'Load HelloComponent'.

We got new directive ngComponentOutlet which does the magic.

If you like the article please do subscribe for more updates on the Angular.