0

I'm trying to refactor my dynamic module loading into a standalone strategy.
In order to use the same route to programmatically load content

Previously I built a module loader to logically load the correct module thus keeping the unused module out of the bundle payload.

In this example it was the public user profile vs an editable profile when the owner is viewing.

<div *ngIf="owner" module-loader selector="post-create"></div>
       
<div *ngIf="!owner" module-loader selector="posts-view"></div>

When it comes to standalone components, are there ways to only load a specific component bundle via routing or even via componentLoader in a template or any other ways?

Ben Racicot
  • 5,332
  • 12
  • 66
  • 130

2 Answers2

0

Here is an example of lazy loaded routes when using standalone components:

import { Routes } from '@angular/router';
import { WelcomeComponent } from './home/welcome.component';

export const routes: Routes = [
  { path: 'welcome', component: WelcomeComponent },
  { path: '', redirectTo: 'welcome', pathMatch: 'full' },
  {
    path: 'products',
    loadChildren: () => import('./products/product.routes').then(r => r.PRODUCT_ROUTES)
  },
  { 
    path: 'about', 
    loadComponent: () => import('./about/about.component').then(c => c.AboutComponent)
  },
  { path: '**', redirectTo: 'welcome', pathMatch: 'full' },
];

You can use loadChildren to load a set of child routes. Angular would then bundle the child routes together into one bundle.

Or you can use loadComponent to load one component. It would then be in it's own bundle.

The output looks like this:

enter image description here

I have a video that walks through this here: https://youtu.be/VzYRFLnnzkE

DeborahK
  • 57,520
  • 12
  • 104
  • 129
  • Hi @DeborahK I watched your video! I'm looking for the URL to stay untouched. I'm thinking of resolving the owner vs visitor then programattically loading the editable version of the profile there vs the read-only. Perhaps this logic in routing is not the place for it. – Ben Racicot Jul 13 '23 at 16:48
  • Consider adding that requirement to your post ... that you don't want the URL to change. – DeborahK Jul 13 '23 at 17:54
0

To load any component programmatically you would use createComponent.

To load a component onto an element:

view
<ng-container #container></ng-container>

controller
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;

this.container.createComponent(SomeComponent);

To load a component into the current component

this.viewContainerRef.createComponent(SomeComponent);

One hangup I had was trying to do this within an activated route observable. You must confirm the element exists in order to call createComponent() on it to load it in. ngAfterViewInit was right for my purposes.

Ben Racicot
  • 5,332
  • 12
  • 66
  • 130