typescript 64 lines · 7 steps

Dynamic component rendering in Angular

A host component that instantiates any component at runtime from a descriptor and keeps its inputs in sync.

Explained by highlit
1import {
2 Component,
3 ComponentRef,
4 Injector,
5 Input,
6 OnChanges,
7 OnDestroy,
8 SimpleChanges,
9 Type,
10 ViewChild,
11 ViewContainerRef,
12} from '@angular/core';
13 
14export interface WidgetDescriptor<T = unknown> {
15 component: Type<T>;
16 inputs?: Partial<Record<keyof T & string, unknown>>;
17}
18 
19@Component({
20 selector: 'app-widget-host',
21 standalone: true,
22 template: '<ng-container #outlet />',
23})
24export class WidgetHostComponent implements OnChanges, OnDestroy {
25 @Input({ required: true }) descriptor!: WidgetDescriptor;
26 
27 @ViewChild('outlet', { read: ViewContainerRef, static: true })
28 private outlet!: ViewContainerRef;
29 
30 private ref?: ComponentRef<unknown>;
31 
32 constructor(private readonly injector: Injector) {}
33 
34 ngOnChanges(changes: SimpleChanges): void {
35 const change = changes['descriptor'];
36 if (!change) return;
37 
38 if (change.currentValue?.component !== change.previousValue?.component) {
39 this.render();
40 } else {
41 this.applyInputs();
42 }
43 }
44 
45 private render(): void {
46 this.outlet.clear();
47 this.ref = this.outlet.createComponent(this.descriptor.component, {
48 injector: this.injector,
49 });
50 this.applyInputs();
51 }
52 
53 private applyInputs(): void {
54 if (!this.ref) return;
55 for (const [key, value] of Object.entries(this.descriptor.inputs ?? {})) {
56 this.ref.setInput(key, value);
57 }
58 this.ref.changeDetectorRef.markForCheck();
59 }
60 
61 ngOnDestroy(): void {
62 this.ref?.destroy();
63 }
64}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1ViewContainerRef.createComponent lets you instantiate components at runtime without declaring them in a template.
  2. 2Comparing currentValue against previousValue in ngOnChanges lets you rebuild only when identity actually changes.
  3. 3Manually created components must be explicitly destroyed and marked for check since Angular won't manage them for you.

Related explainers

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
typescript
import { useEffect, useState } from "react";
 
interface Section {
  id: string;

Building a scroll-spy hook in React

custom-hooks intersectionobserver dom-observation
Intermediate 8 steps
typescript
import { Injectable, Scope, Inject, NotFoundException } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';
import { DataSource } from 'typeorm';

Per-tenant database connections in NestJS

multi-tenancy connection-pooling dependency-injection
Advanced 8 steps

Share this explainer

Here's the card — post it anywhere.

Dynamic component rendering in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code