Skip to content
tezvyn:
Menu

Angular: Dynamic Component Loading

Source: angular.devHardHow cards are made

Angular: Dynamic Component Loading

Programmatically create and render components anywhere in your app, not just where you've hardcoded them. Use it for dynamic dashboards or modal dialogs. The footgun is forgetting to manually destroy components, which leads to memory leaks.

Why it exists

Static HTML templates are rigid. They define a fixed structure at compile time. Dynamic component loading solves the problem of building UIs where parts of the view are unknown until runtime, such as a dashboard with user-configurable widgets or a CMS rendering a page from an array of different content blocks.

The mental model

Imagine your template has a designated, empty placeholder. Dynamic loading lets you get a programmatic handle to this placeholder and then, on command, create a new component instance and insert it there. You are manually performing the steps that Angular's compiler usually does automatically when it finds a component selector in a template.

How it works

First, you define an anchor point in a template, typically an <ng-container> with a template reference variable, like <ng-container #dynamicHost></ng-container>. In your component class, you get access to this anchor using @ViewChild('dynamicHost', { read: ViewContainerRef }). The ViewContainerRef is the programmatic handle to that placeholder. To add a component, you call viewContainerRef.createComponent(MyDynamicComponent). This returns a ComponentRef, which represents the live instance of the component. You can use this reference to pass data to its inputs or subscribe to its outputs. Crucially, you must call componentRef.destroy() when the component is no longer needed to remove it from the DOM and avoid memory leaks. This is often done in the ngOnDestroy lifecycle hook of the host component.

When to use it

Use this for highly dynamic UIs. Three common cases are: first, building a dashboard where users can add, remove, and reorder different widgets; second, creating a generic modal service that can display any component inside a dialog box; third, rendering pages from a JSON structure, where each object in the JSON maps to a different component type.

When not to use it

Do not use it for simple conditional rendering; @if (or ngIf) is far simpler and more efficient. Don't use it for rendering a list of the same component; @for (or ngFor) is the correct tool for that. It adds complexity, so avoid it unless the content is truly determined at runtime and cannot be handled declaratively.

One canonical example

A tabbed interface where each tab's content is a different, complex component. When a user clicks a new tab, the host component clears its ViewContainerRef (destroying the old component) and then creates and injects the component corresponding to the newly selected tab.

Interview question

Which scenario is the most appropriate use case for Angular's dynamic component loading?

  • a.Implementing a flexible modal dialog service capable of showing different component types.Correct
  • b.Displaying a component only when a specific condition is met, like a user being logged in.
  • c.Rendering a list of product cards where each card uses the same component template.
  • d.Reducing the initial bundle size by loading components only when their route is activated.
Why?

Dynamic component loading is ideal for highly dynamic UIs where component types are unknown until runtime, such as a generic modal service displaying various components. Options A and B describe scenarios best handled by Angular's declarative @if and @for directives, respectively, which are explicitly mentioned as cases not to use dynamic loading. Option D refers to route-based lazy loading, a different optimization technique.

Just read this? Test yourself on what you have been reading.

Read the original → angular.dev

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on angular — each one lists the topics its interview covers.

See open roles