angular / 14 / api / core / createcomponent.html

createComponent

function

Creates a ComponentRef instance based on provided component type and a set of options.

createComponent<C>(component: Type<C>, options: { environmentInjector: EnvironmentInjector; hostElement?: Element; elementInjector?: Injector; projectableNodes?: Node[][]; }): ComponentRef<C>

Parameters
component Type<C>

Component class reference.

options object

Set of options to use:

Returns

ComponentRef<C>: ComponentRef instance that represents a given Component.

Usage notes

The example below demonstrates how the createComponent function can be used to create an instance of a ComponentRef dynamically and attach it to an ApplicationRef, so that it gets included into change detection cycles.

Note: the example uses standalone components, but the function can also be used for non-standalone components (declared in an NgModule) as well.

@Component({
  standalone: true,
  template: `Hello {{ name }}!`
})
class HelloComponent {
  name = 'Angular';
}

@Component({
  standalone: true,
  template: `<div id="hello-component-host"></div>`
})
class RootComponent {}

// Bootstrap an application.
const applicationRef = await bootstrapApplication(RootComponent);

// Locate a DOM node that would be used as a host.
const host = document.getElementById('hello-component-host');

// Get an `EnvironmentInjector` instance from the `ApplicationRef`.
const environmentInjector = applicationRef.injector;

// We can now create a `ComponentRef` instance.
const componentRef = createComponent(HelloComponent, {host, environmentInjector});

// Last step is to register the newly created ref using the `ApplicationRef` instance
// to include the component view into change detection cycles.
applicationRef.attachView(componentRef.hostView);

© 2010–2023 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v14.angular.io/api/core/createComponent