hardFrontend

How do you dynamically create components?

454 views
01

Understand the problem

Explain dynamic component loading.

dynamic-components
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Create and configure a component at runtime
import { Component, ViewChild, ViewContainerRef, AfterViewInit } from '@angular/core';

@Component({ selector: 'app-widget', standalone: true, template: '<b>{{ title }}</b>' })
export class WidgetComponent { title = ''; }

@Component({
  selector: 'app-root',
  standalone: true,
  template: '<ng-container #host></ng-container>',
})
export class AppComponent implements AfterViewInit {
  @ViewChild('host', { read: ViewContainerRef }) host!: ViewContainerRef;

  ngAfterViewInit() {
    const ref = this.host.createComponent(WidgetComponent); // instantiate
    ref.setInput('title', 'Created at runtime');            // pass input
    // ref.destroy();  // when finished → cleanup
  }
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.