Content projection, what is it?

Carlos Caballero
Jun 6 · 3 min read

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

Therefore, using content projection, you can obtain the result shown in the following image.

Notice that the component works like a mirror. Another more complicated example is the one shown in the following image in which a letter with user data is being configured.

What is a ng-container?

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.

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

am-icon is the following component:

The result is one icon instead of four, just as we expected.

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…

What is a ng-template?

As the name suggests, it is a template element: a model which you can instantiate. Therefore, 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 it with: *ngIf, *ngFor, *anyDirective, …

Then our repeat component?

What is that ngTemplateOutlet?

The ngTemplateOutlet directive receives a ng-template. It’s responsible for creating the instance and inserting it into the DOM.

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, etc.).

We Can Do Awesome Things!

More more more…

Better Programming

Advice for programmers.

Carlos Caballero

Written by

Hi! My name is Carlos Caballero and I’m PhD. in Computer Science from Málaga, Spain. Teaching developers and degree/master computer science how to be experts!

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade