How ng-content and selector can help you ?

When you want to add dynamic content in a fixed view template, you should think Transclusion. This mecanism allow you to define a hook for dynamic content by using <ng-content> tag.  For exemple, CardComponent is a component that uses this mechanism : 

We can see this component as a template. Now, here's how to use it :

You can see the result :

Ok, it's fine but how to define several transclusions ? With select attribute of course ! The select attribut allows us to sort of name our <ng-content>, this is the selector of our tag. Let's see it :

Now, here's how to use it :

You can see the result :

 

Selectors are very interesting, you can define different patterns of selection. Here are some examples on how you can use that : 
 

  • select with attribut :

<ng-content select="[card-header]"></ng-content>  

— How to use it –>    <div card-header>Card body</div>

 

  • select as  multiple attributes

<ng-content select="[card][header]"></ng-content>

— How to use it –> <p card header>Multi attributes</p>

 

  • select as css class

 <ng-content select="div[class=card-body]"></ng-content>  

— How to use it –> <div class="card-body">select as css class</div>

 

<ng-content select=".card-body"></ng-content>

— How to use it –> <div class="card-body">select as css class</div>

 

  • select as multiple class

 <ng-content select="div[class=card-block card-body]"></ng-content>

— How to use it –>  <div class="card-block card-body">select as Multi css class</div>

 

  • select as attribute with value

 <ng-content select="[card-type=body]"></ng-content>  

— How to use it –>  <p card-type="body">Multi attribute</p>

 

  • select as html tag

 <ng-content select="card-body"></ng-content>  

— How to use it –>   <card-body class="card-block">Content 5</card-body> 

 

If you use selector with HTML tag, we should add schema metadata property in your module, set value to NO_ERRORS_SCHEMA in your module file.

Now it's your turn ! 

William Koza

William Koza

Consultant Indépendant chez  
Passionné par la conception et le développement logiciel, j’ai rapidement pris le rôle de Technical Leader lors de mes premiers projets. Ces expériences ont ainsi pu me faire accéder à des rôles d’architecte dans des projets d’envergure. Aujourd'hui, j'exerce mon métier en tant qu'indépendant, et toujours avec la même passion.
William Koza

Les derniers articles par William Koza (tout voir)