Monthly Archives: February 2017

ng-content with Angular2 (Transclusion) – AngularCli

ng-content with Angular2 (Transclusion) – AngularCli

In this post we are going to look at a special feature in Angular2. The feature allows to create templates such that parent components can inject parts into the view of the child component. The child components use the injected part using ng-content.

When should we use ng-content?

  • ng-content is specially useful when you have pre-built components which you want to use throughout your application.
  • This are also suitable when a component needs to inject some elements into the display area of another component.

Let’s create a sample application Angular2TransclusionApp using Angular CLI.

ng new Angular2TransclusionApp

Here is how it generates the necessary files for our project:

ng new Angular2TransclusionApp

ng new Angular2TransclusionApp

Now we add another component to the app. Let’s call it MyCardComponent.

ng generate component MyCardComponent

Let’s just update the template of the card component. We are just using the content and decorating it using our best artistic skills. We are turning the background to yellow. Additionally, we are adding a border to it and coloring it lightgreen. Isn’t it beautiful…

Let’s just use the card component in our app component. We are just adding a div to the card’s content. The div just has some text inside. And yes I am using my name as the component, because I can…

Let’s run it using ng serve. This is certainly an amazing display of my craft.

ng-content display

ng-content display

Transclusion Using Selectors

We can also use multiple ng-content (s) within the same component. Let’s create a new component.

ng generate component my-special-card

ng generate component my-special-card

The component template has multiple ng-content (s). We use select to pick the relevant content. This also supports CSS classes by using DOT (.) notation.

Here we are using the component in the main App component. You can see that we are using the names for two contents while the third component is specified using CSS class.

Let’s run this now.

My Special card

My Special card

Source Code

Source code on github

Source code on github