Performance: Dynamic component loading
This affects the initial page load speed and interaction responsiveness by controlling when and how components are loaded and rendered.
Jump into concepts and practice - no test required
import { ViewContainerRef, Component } from '@angular/core'; @Component({ selector: 'app-root', template: `<ng-template #container></ng-template>` }) export class AppComponent { constructor(private vcr: ViewContainerRef) {} async loadComponent() { const { ComponentA } = await import('./component-a'); this.vcr.clear(); this.vcr.createComponent(ComponentA); } }
import { ComponentA } from './component-a'; @Component({ selector: 'app-root', template: `<component-a></component-a>` }) export class AppComponent {}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Static import and render | High (all components created at start) | Multiple (due to many components) | High (all painted immediately) | [X] Bad |
| Dynamic import with lazy loading | Low (only loaded components created) | Single or few (on-demand) | Low (only painted when needed) | [OK] Good |
const componentRef = viewContainerRef.createComponent(MyComponent); componentRef.instance.title = 'Hello';
MyComponent displays {{ title }} in its template.instance.title assigns the property used in the template.{{ title }} is displayed, and title is set to 'Hello', the text 'Hello' will appear.@ViewChild('container', { read: ViewContainerRef }) containerRef!: ViewContainerRef;
load() {
const comp = this.containerRef.createComponent(SomeComponent);
comp.instance.data = 'Test';
}#container expects a matching template reference variable in HTML.#container is missing in the template, containerRef will be undefined, causing runtime errors.#container template reference in HTML -> Option DcreateComponent() with the chosen component type each time, clearing previous components -> Option A