Angular2 pass dynamic content to a component

2019-09-14 16:39发布

问题:

I have a ListComponent that basically loops on an array of objects with ngFor + some functionality.

I would like to be able to pass different 'item' components as content of the ListComponent like this:

<list-component>
    <item-component [SomeInput]="someInput">
        <some-content></some-content>
    </item-component>
</list-component>

and in another place:

<list-component>
     <different-item-component [SomeInput]="someInput">
         <some-content></some-content>
     </different-item-component>
</list-component>

and then in my ListComponent

<ul>
    <li *ngFor="let item of items">
        <!-- ng-content can be different item components -->
        <ng-content [Item]="item" ></ng-content>
    </li>
</ul>

I know that ng-content is static and the item can't be passed as input. (It's just to illustrate the wanted behavior...)

I've tried to achieve this using template and TemplateRef like in this answer

but it only works if I place the template tag directly inside the <list-component> doesn't work if I place the template inside the item-component's template and use it as above.

How can I make it work or is there a different way to achieve this?