angularangular-templatetransclusion

Angular transclusion without wrapping tag


How can one make slot transclusion in Angular without including wrapping tag?

For example:

Here is template of component with selector my-component:

<div class="my-component">
   <p class="some sensitive css-classes">
       <ng-content select="sub-header"></ng-content>
   </p>

   <p class="more sensitive css-classes">
       <ng-content select="sub-footer"></ng-content>
   </p>
</div>

This was one of the components which filled in the template with data

<my-component>
    <sub-header>
        Very <strong>important</strong> text with tags.
    </sub-header>

    <sub-footer>
        More <em>important</em> text with tags.
    </sub-footer>
</my-component>

The transclusion result looks so:

<div class="my-component">
   <p class="some sensitive css-classes">
       <sub-header>
          Very <strong>important</strong> text with tags.
       </sub-header>
   </p>

   <p class="more sensitive css-classes">
       <sub-footer>
           More <em>important</em> text with tags.
       </sub-footer>
   </p>
</div>

This is not very useful, because of semantics and in case of very sensitive CSS-styles

How can I get transclusion which looks like this:

<div class="my-component">
   <p class="some sensitive css-classes">
       Very <strong>important</strong> text with tags.
   </p>

   <p class="more sensitive css-classes">
       More <em>important</em> text with tags.
   </p>
</div>

The main difference from other questions is the transclusion of dom.


Solution

  • You can use ngProjectAs angular attribute on ng-container tag

    <my-component>
      <ng-container ngProjectAs="sub-header">
        Very 
        <strong>important</strong> text with tags.
      </ng-container>
      <ng-container ngProjectAs="sub-footer">
        More 
        <em>important</em> text with tags.
      </ng-container>
    </my-component>
    

    Stackblitz Example

    For documentation take a look at https://github.com/angular/angular.io/issues/1683