liveBook · Manning

createComponent

As explained in Pro Angular 16

createComponent is a ViewContainerRef method that creates an Angular component dynamically at a view-container location.

createComponent creates an Angular component instance. Its role depends on context: ViewContainerRef can use it to select a component programmatically, while TestBed uses it to instantiate a component for unit tests. section 29.4.1 section 16.2.2

Use createComponent in two distinct situations:

  • Call TestBed.createComponent(SimpleComponent) after configuring the testing module. The result is a ComponentFixture, and its componentInstance property exposes the created component. section 29.4.1
  • Call ViewContainerRef.createComponent to select a component programmatically instead of declaring a fixed element in a template. section 16.2.2
  • Treat dynamic component creation cautiously because the discussed approach is described as limited and potentially more troublesome than useful. section 16.2.2

Creating a component for a unit test

Configure the test module inside beforeEach, declare SimpleComponent, and create the fixture there: fixture = TestBed.createComponent(SimpleComponent); component = fixture.componentInstance;. A basic test can then verify that component is defined. The fixture also provides debugElement, nativeElement, detectChanges(), and whenStable() for further testing.

How Pro Angular 16 covers it

How deep it goes
Explains testing setup and fixture access, but treats dynamic loading briefly and defers implementation details to Angular documentation.
Examples
Uses SimpleComponent tests, TestBed configuration, componentInstance access, and fixture change-detection utilities.
What it assumes
Assumes Angular components and testing basics, while demonstrating test-module configuration and dependency provisioning.
What you can do after
Apply it via TestBed to instantiate a component and inspect its instance or fixture during unit tests.
How it connects
Connects createComponent with TestBed, ViewContainerRef, ComponentFixture, unit testing, and dependency injection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.