Angular transclusion without wrapping tag
Asked Answered
F

1

5

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.

Fortitude answered 21/12, 2017 at 17:57 Comment(1)
Possible duplicate of Remove the host HTML element selectors created by angular componentMadalena
D
11

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

Doting answered 21/12, 2017 at 18:5 Comment(7)
It looks not very clean, but it works!!! If there comes no better solution, I will accept this as the answer!Fortitude
where is this even documented!? :DPerhaps
@Perhaps Added :)Doting
You will probably need to use ng-container or ng-template. ` blog.angular-university.io/…Robbierobbin
Kinda dissapointing to see that there is no documentation about this, as there isnt a place designated for it (since already v2) github.com/angular/angular.io/pull/2851. For anyone looking for more info check medium.com/claritydesignsystem/…Perhaps
@Perhaps Thanks. That is a great articleDoting
Brilliant, I have been looking for ages how to do this.Murcia

© 2022 - 2024 — McMap. All rights reserved.