Bird
Raised Fist0
Angularframework~20 mins

Dynamic component loading in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Dynamic Loader Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when dynamically loading a component with Angular signals?
Consider an Angular standalone component that uses signals to dynamically load another component into a . What will be the rendered output if the signal controlling the component type changes?
Angular
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-dynamic-loader',
  standalone: true,
  template: `
    <ng-container *ngIf="currentComponent() as comp">
      <ng-container *ngComponentOutlet="comp"></ng-container>
    </ng-container>
    <button (click)="toggle()">Toggle Component</button>
  `
})
export class DynamicLoaderComponent {
  private compA = class {
    static ɵcmp = { selectors: [['comp-a']], template: function() { document.write('Component A Loaded'); } };
  };
  private compB = class {
    static ɵcmp = { selectors: [['comp-b']], template: function() { document.write('Component B Loaded'); } };
  };

  currentComponent = signal(this.compA);

  toggle() {
    this.currentComponent.set(this.currentComponent() === this.compA ? this.compB : this.compA);
  }
}
ABoth components render simultaneously inside the container.
BThe component does not render anything because signals cannot be used with *ngComponentOutlet.
CClicking the button causes a runtime error because the component classes are not registered.
DInitially 'Component A Loaded' is shown. Clicking the button switches the output to 'Component B Loaded'.
Attempts:
2 left
💡 Hint
Think about how signals update reactive values and how *ngComponentOutlet uses the current component reference.
📝 Syntax
intermediate
1:30remaining
Which option correctly uses Angular 17+ inject() to dynamically load a component?
Given Angular 17+ with standalone components and inject(), which code snippet correctly injects a ViewContainerRef to load a component dynamically?
A
const vcr = inject(ViewContainerRef);
vcr.createComponent(MyComponent);
B
const vcr = new ViewContainerRef();
vcr.createComponent(MyComponent);
C
const vcr = inject(MyComponent);
vcr.createComponent(ViewContainerRef);
D
const vcr = inject(ViewContainerRef);
vcr.loadComponent(MyComponent);
Attempts:
2 left
💡 Hint
inject() is used to get Angular dependencies, not to create new instances with new.
🔧 Debug
advanced
2:30remaining
Why does this dynamic component loading code cause a runtime error?
Analyze the following Angular code snippet that tries to load a component dynamically but throws an error at runtime. What is the cause?
Angular
import { Component, ViewChild, ViewContainerRef } from '@angular/core';

@Component({
  selector: 'app-host',
  template: `<ng-template #container></ng-template>`
})
export class HostComponent {
  @ViewChild('container', { read: ViewContainerRef }) container!: ViewContainerRef;

  ngAfterViewInit() {
    this.container.createComponent(SomeComponent);
  }
}

@Component({
  selector: 'app-some',
  template: `<p>Some works!</p>`
})
export class SomeComponent {}
ASomeComponent is not declared in any NgModule or standalone, so Angular cannot resolve it.
BThe ViewChild query is missing { static: true }, causing container to be undefined.
CcreateComponent requires a factory, not the component class directly.
DngAfterViewInit runs too early; dynamic loading should be in ngOnInit.
Attempts:
2 left
💡 Hint
Check if the component being loaded is properly registered or standalone.
state_output
advanced
2:00remaining
What is the output after toggling dynamic components twice?
Given this Angular component that toggles between two dynamically loaded components on button click, what will be the output after clicking the toggle button twice?
Angular
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-toggle',
  standalone: true,
  template: `
    <ng-container *ngComponentOutlet="current()"></ng-container>
    <button (click)="toggle()">Toggle</button>
  `
})
export class ToggleComponent {
  comp1 = class {
    static ɵcmp = { selectors: [['comp-1']], template: function() { document.write('First Component'); } };
  };
  comp2 = class {
    static ɵcmp = { selectors: [['comp-2']], template: function() { document.write('Second Component'); } };
  };

  current = signal(this.comp1);

  toggle() {
    this.current.set(this.current() === this.comp1 ? this.comp2 : this.comp1);
  }
}
AAfter two toggles, both components are displayed simultaneously.
BAfter two toggles, 'First Component' is displayed again.
CAfter two toggles, 'Second Component' remains displayed.
DAfter two toggles, the component container is empty.
Attempts:
2 left
💡 Hint
Think about how toggling twice switches the component back to the original.
🧠 Conceptual
expert
3:00remaining
Which statement best describes Angular's dynamic component loading with standalone components and signals?
Select the statement that accurately explains how Angular 17+ supports dynamic component loading using standalone components and signals.
ASignals cannot be used with dynamic component loading; only ViewContainerRef.createComponent is supported.
BDynamic component loading requires NgModules to declare components; standalone components cannot be loaded dynamically.
CSignals can hold component classes, and templates using *ngComponentOutlet reactively update when the signal changes, enabling seamless dynamic loading without NgModules.
DAngular requires manual change detection calls after dynamic component loading with signals to update the view.
Attempts:
2 left
💡 Hint
Consider Angular's move towards standalone components and reactive primitives like signals.

Practice

(1/5)
1. What is the main purpose of dynamic component loading in Angular?
easy
A. To add components to the view while the app is running
B. To statically declare all components in the template
C. To improve CSS styling of components
D. To replace Angular modules with components

Solution

  1. Step 1: Understand dynamic component loading

    Dynamic component loading means adding components to the app view during runtime, not just at compile time.
  2. Step 2: Compare options

    Only To add components to the view while the app is running describes adding components while the app runs. Other options describe static or unrelated concepts.
  3. Final Answer:

    To add components to the view while the app is running -> Option A
  4. Quick Check:

    Dynamic loading = add components at runtime [OK]
Hint: Dynamic loading means adding components during app run [OK]
Common Mistakes:
  • Confusing dynamic loading with static template declaration
  • Thinking it changes CSS or modules
  • Assuming it replaces Angular modules
2. Which Angular service is used to insert a dynamic component into the view?
easy
A. Renderer2
B. HttpClient
C. ViewContainerRef
D. NgModuleRef

Solution

  1. Step 1: Identify the service for dynamic insertion

    ViewContainerRef provides a container where components can be dynamically added or removed.
  2. Step 2: Eliminate other options

    Renderer2 is for DOM manipulation, HttpClient for HTTP calls, NgModuleRef for module references, none for dynamic component insertion.
  3. Final Answer:

    ViewContainerRef -> Option C
  4. Quick Check:

    Dynamic insertion uses ViewContainerRef [OK]
Hint: Use ViewContainerRef to insert dynamic components [OK]
Common Mistakes:
  • Choosing Renderer2 which is for DOM, not components
  • Confusing HttpClient with component loading
  • Using NgModuleRef incorrectly
3. Given this code snippet, what will be the output in the browser?
const componentRef = viewContainerRef.createComponent(MyComponent);
componentRef.instance.title = 'Hello';

Assuming MyComponent displays {{ title }} in its template.
medium
A. The component will load but title will be empty
B. The text 'Hello' will appear where the component is loaded
C. Nothing will appear because the component is not attached
D. An error because title is not a valid property

Solution

  1. Step 1: Understand createComponent and instance property

    createComponent adds the component to the view. Setting instance.title assigns the property used in the template.
  2. Step 2: Predict rendered output

    Since {{ title }} is displayed, and title is set to 'Hello', the text 'Hello' will appear.
  3. Final Answer:

    The text 'Hello' will appear where the component is loaded -> Option B
  4. Quick Check:

    Set instance property = visible text [OK]
Hint: Setting instance properties updates displayed content [OK]
Common Mistakes:
  • Thinking component is not attached after createComponent
  • Assuming property must be declared differently
  • Ignoring that instance properties affect template
4. What is wrong with this code snippet for dynamic component loading?
@ViewChild('container', { read: ViewContainerRef }) containerRef!: ViewContainerRef;

load() {
  const comp = this.containerRef.createComponent(SomeComponent);
  comp.instance.data = 'Test';
}
medium
A. ViewChild should not use read option
B. Using createComponent without importing ComponentFactoryResolver
C. Cannot assign data property on instance
D. Missing #container template reference in HTML

Solution

  1. Step 1: Check ViewChild usage

    ViewChild with #container expects a matching template reference variable in HTML.
  2. Step 2: Identify missing template reference

    If #container is missing in the template, containerRef will be undefined, causing runtime errors.
  3. Final Answer:

    Missing #container template reference in HTML -> Option D
  4. Quick Check:

    ViewChild needs matching template ref [OK]
Hint: Always add matching #ref in template for ViewChild [OK]
Common Mistakes:
  • Assuming ComponentFactoryResolver is needed in Angular 14+
  • Thinking instance properties can't be assigned
  • Misusing read option in ViewChild
5. You want to load different components dynamically based on user input. Which approach correctly handles this scenario in Angular?
hard
A. Use a single ViewContainerRef and call createComponent() with the chosen component type each time, clearing previous components
B. Declare all possible components in the template and use *ngIf to show/hide them
C. Create components manually with new keyword and append to DOM
D. Use Angular modules to switch components dynamically without ViewContainerRef

Solution

  1. Step 1: Understand dynamic component switching

    Using ViewContainerRef with createComponent allows loading different components at runtime by clearing old ones and adding new.
  2. Step 2: Evaluate other options

    Declare all possible components in the template and use *ngIf to show/hide them is static and less flexible. Create components manually with new keyword and append to DOM bypasses Angular and breaks framework rules. Use Angular modules to switch components dynamically without ViewContainerRef misunderstands modules' role.
  3. Final Answer:

    Use a single ViewContainerRef and call createComponent() with the chosen component type each time, clearing previous components -> Option A
  4. Quick Check:

    Dynamic switching = clear + createComponent [OK]
Hint: Clear container then create chosen component dynamically [OK]
Common Mistakes:
  • Using static *ngIf instead of dynamic loading
  • Trying to create components with new keyword
  • Confusing modules with dynamic component loading