Things Worth Knowing About Dynamic Components in Angular

Netanel Basal
Netanel Basal
Published in
2 min readNov 16, 2018

--

In this article, I would like to answer a question that was asked yesterday on Twitter by Sani Yusuf and also add more interesting points.

When we dynamically create a component and insert it into the view by using a ViewContainerRef, Angular will invoke each one of the lifecycle hooks except for the ngOnChanges() hook.

The reason for that is the ngOnChanges hook isn’t called when inputs are set programmatically only by the view.

Here is an example for dynamic component creation:

So in this case, the answer is Yes, Angular destroys the component when the parent has been destroyed.

One more important thing to consider is that if we subscribe manually to a component’s @Output(), we need to clean it by ourselves otherwise we’ll have a memory leak. For example:

Let’s change the HelloComponent and set its change detection to onPush :

Now, let’s try to change the name input and call detectChanges() :

Nothing is happening. But why? We’re running detectChanges() explicitly so it should work, right?

The reason is that we’re running detectChanges() on the host view, not on the component itself and because we’re in onPush and setting the input programmatically from Angular perspective nothing has changed.

We have two solutions to this problem. We can inject the CDRef in our component and call it in the setter:

Or we can get a reference to the component injector:

The above point also happens with non-dynamic components, but the essential point to take from here is that when we call ref.changeDetectorRef.detectChanges() or ref.hostView.detectChanges() we are invoking the CDR of the host view.

My friend Max, Wizard of the Web also add that if we attach the host view to the ApplicationRef (portals, etc.), we need to destroy it manually. For example:

I will also add that in this case, unlike the first case, we need to call detectChanges() in order to invoke the ngOnInit().

🔥 Last but Not Least, Have you Heard of Akita?

Akita is a state management pattern that we’ve developed here in Datorama. It’s been successfully used in a big data production environment, and we’re continually adding features to it.

Akita encourages simplicity. It saves you the hassle of creating boilerplate code and offers powerful tools with a moderate learning curve, suitable for both experienced and inexperienced developers alike.

I highly recommend checking it out.

Follow me on Medium or Twitter to read more about Angular, Akita and JS!

--

--

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.