ng-template, ngTemplateOutlet and ngTemplateOutletContext | Learn Angular

laptop computer on glass-top table

This is the first article of a new section exposing various problems that can be found and obviously how to answer them. There is no need to look for an order in these articles, it’s just a collection of tips and tricks.

Problematic

The problem is rather simple at first glance :  Create a menu / sub menu system. We’re going to create a component Menu, then a component SubMenu. Obviously, our menu had to be retractable according to any condition. So let’s go !

It’s seem to work but take a look at the console ! The Life cycle of SubMenu component isn’t bind to Menu component, so our SubMenu components are created even if the menu is not open! Similary, when the menu get closes, Submenu component  have not been destroyed. This problem has often been reported but it is a design choice.

This solution is therefore not ideal, we must think of another solution !

Solution

When you are faced with this kind of problem, you have to think about the tag. You use it, maybe without realizing it, when you use the structural directives *ngIf, *ngFor … Angular offers the NgTemplateOutlet directive which embeds the template in a tag. It is also possible to add context using the ngTemplateOutletContext directive. Its use is rather simple : just declare a template with the code that we want to see re-use, then it is possible to embed it in an another tag of your choice. Here is an example of use:

In our case, We’re going to modify our first code using the NgTemplateOutlet directive like this:

And now, if we take a look at the console, we can notice that our component SubMenu is well created and destroyed according to the status of the menu.

Laisser un commentaire