Bird
Raised Fist0
Angularframework~10 mins

Dynamic component loading in Angular - Interactive Code Practice

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
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the Angular core module needed for dynamic component loading.

Angular
import { [1] } from '@angular/core';
Drag options to blanks, or click blank then click option'
ANgModule
BInjectable
CComponentFactoryResolver
DDirective
Attempts:
3 left
💡 Hint
Common Mistakes
Importing NgModule instead of ComponentFactoryResolver
Using Injectable which is for services
Using Directive which is for attribute or structural directives
2fill in blank
medium

Complete the code to get a reference to the container where the dynamic component will be inserted.

Angular
@ViewChild('container', { read: [1] }) containerRef!: ViewContainerRef;
Drag options to blanks, or click blank then click option'
ATemplateRef
BViewContainerRef
CElementRef
DRenderer2
Attempts:
3 left
💡 Hint
Common Mistakes
Using ElementRef which references DOM elements but not containers
Using TemplateRef which is for templates, not containers
Using Renderer2 which is for DOM manipulation
3fill in blank
hard

Fix the error in the code to create a component dynamically using the resolver.

Angular
const factory = this.componentFactoryResolver.[1](MyDynamicComponent);
this.containerRef.clear();
this.containerRef.createComponent(factory);
Drag options to blanks, or click blank then click option'
AresolveComponentFactory
BcreateComponentFactory
CgetComponentFactory
DmakeComponentFactory
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent methods like createComponentFactory
Using getComponentFactory which does not exist
Using makeComponentFactory which is invalid
4fill in blank
hard

Fill both blanks to clear the container and insert the new component.

Angular
this.containerRef.[1]();
this.containerRef.[2](factory);
Drag options to blanks, or click blank then click option'
Aclear
BcreateComponent
Cinsert
Dremove
Attempts:
3 left
💡 Hint
Common Mistakes
Using remove instead of clear to empty the container
Using insert instead of createComponent to add the component
5fill in blank
hard

Fill all three blanks to define a dynamic component loader method that creates and inserts a component.

Angular
loadComponent() {
  const factory = this.[1].[2](DynamicComponent);
  this.containerRef.[3]();
  this.containerRef.createComponent(factory);
}
Drag options to blanks, or click blank then click option'
AcomponentFactoryResolver
BresolveComponentFactory
Cclear
DcreateComponent
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong service name for the resolver
Skipping clearing the container before insertion
Using wrong method names

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