Skip to main content

How do hooks work for dynamically created components?

In Angular, the lifecycle hooks for dynamically created components work exactly the same way as for regular components, except that the component is created programmatically through ComponentFactory or ViewContainerRef.

Key points

  1. Creating a dynamic component:
ts
const factory = this.resolver.resolveComponentFactory(MyComponent); const componentRef = this.container.createComponent(factory);
  • componentRef.instance is the component instance.
  1. Calling the hooks:
  • ngOnChanges() - called if values are passed through @Input after the component is created.
  • ngOnInit(), ngDoCheck(), ngAfterContentInit(), ngAfterViewInit(), and the other hooks - called automatically by Angular after the component is created, in the correct order.
  • ngOnDestroy() - called when you remove the component manually through componentRef.destroy().
  1. Peculiarities:
  • If you create a component dynamically, the hooks fire only after it is inserted into the container (ViewContainerRef).
  • To manage input data (@Input), you need to assign it before or immediately after creation, otherwise ngOnChanges might not fire.

In other words, for dynamically created components, the lifecycle is fully respected, you just control the moment of creation and removal yourself, and Angular calls the hooks in the same order as for statically declared components.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.