Search code examples
angularangular-components

How to use content projection (aka transclusion) in Angular


I am new to angular 4.

I have a doubt in angular 4 embedded components.

example:

<hero-list>
    <hero></hero>
    <hero></hero>
</hero-list>

I wanted to know how to create a view based on this structure that is embedding component inside another component.


Solution

  • You should use <ng-content></ng-content> in your hero-list-component. So you can realize your wish above.

    hero-list.component.html

    <div class="hero-list">
      <h1>Hero list</h1>
      <ng-content></ng-content>
    </div>
    

    And now you can wrap your hero-item-components and they will be printed inside of hero-listcomponent.

    app.component.html

    <hero-list>
      <hero-item></hero-item>
      <hero-item></hero-item>
    </hero-list>
    

    Here is working example: https://stackblitz.com/edit/angular-nvpmtc

    And here is a good article about content projection in angualr.