Angular's ng-template and transclusion

  • Web Developer
  • Computer Science Student
  • PhD. Computer Science
  • Computer Science Teacher


Let's start!

Content projection, what is it?

"Content projection (also known as transclusion) is a way to import HTML content from outside the component and insert that content into the component's template in a designated spot."

Ok... show me the code!!

It's very simple

I saw a ng-container, what is that?

"The Angular ng-container is a grouping element (syntax element) that doesn't interfere with styles or layout because Angular doesn't put it in the DOM."

And we can use structural directives with it.

Structural... What?

"A Structural directive changes the DOM layout by adding, removing or manipulating DOM elements."

And then can I...?

Nope 💔

How does ng-content work?

  • ng-content doesn't produce content. It simply projects the existing content
    • consistency of expectations 👀
    • performance 🔥
  • Following the previous rule, it can neither create nor destroy components projected (lifecycle)
  • Only the last ng-content projects the content

And... what can I do?

Here ng-template comes to the rescue...

That sounds good.

Give me more!

Okaay, then what is a ng-template?

As the name suggests, it is a template element, a model which you can instantiate, hence you can set a template as a component's input, which is pretty useful.

The asterisk (*) syntax

"The asterisk is syntactic sugar for something a bit more complicated."

You usually see with: *ngIf, *ngFor, *anyDirective,...

Then our repeat component?

Spidy is happy again ❤️

And I? Explain me what that ngTemplateOutlet is!

The ngTemplateOutlet directive receives a ng-template and it's responsible for create the instance and insert it into the DOM.

But there are more!

Yeah, context like in JS!

  • We can give an object to the instance, which is created by the ngTemplateOutlet, of your ng-template.
  • That object can contain whatever you want to pass to your template.
  • Here, we expose the magic of a lot of library components (datatables, angular-material, ng-bootstrap,...).

We can do awesome things!


Thank You