Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy loading Angular 13+ modules without the deprecated compiler

I've worked extensively with loading and instantiating Angular modules. (without the router)

But now with Angular 13 I'm seeing deprecations for the usual compiler tools to instantiate an NgModule:

enter image description here

Here is my usual go-to code for loading a module

const moduleFactory = await this.compiler.compileModuleAsync(module);
const moduleRef = moduleFactory.create(this.injector);
const componentFactory = moduleRef.instance.resolveComponent(selector);

Looking deeper The V13 change where ViewContainerRef now has the factory included makes dynamic components 1 step easier. However, regarding ViewContainerRef.createComponent() the documentation states:

Deprecated Angular no longer requires component factories to dynamically create components. Use different signature of the createComponent method, which allows passing Component class directly.

So what are the new directions for these tasks in Angular 13+?

like image 527
Ben Racicot Avatar asked Mar 07 '26 07:03

Ben Racicot


1 Answers

You can leverage a new createNgModule method and replace these steps:

const moduleFactory = await this.compiler.compileModuleAsync(module);
const moduleRef = moduleFactory.create(this.injector);

with

const moduleRef = createNgModule(module, this.injector);

You can also read about all deprecations and possible replacement in Angular doc https://angular.io/guide/deprecations

like image 107
yurzui Avatar answered Mar 09 '26 22:03

yurzui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!