I\'m using Angular 2-rc3 and have a Component
and I want to apply transclusion, just in a bit of a different way. Here\'s my component:
import {
<ng-content>
inside *ngFor
doesn't work, therefore
<li *ngFor="let item of data">
-- insert template here --
<ng-content></ng-content>
</li>
won't do anything meaningful. Everything will be transcluded to the first <ng-content>
https://github.com/angular/angular/issues/8563 might solve some of your requirements.
<template>
tag.To spell out the ngForTemplate
method:
(As of Angular 4 the element is now called <ng-template>
.)
Use a <template>
tag in both the outer and inner components, instead of <ng-content>
.
The <li>
is moved to the app.component html, and the <template>
on this component has a special 'let-' attribute which references the iterated variable in the inner component:
<my-list [data]="cars">
<template let-item>
<li>
<div>{{item.make | uppercase}}</div>
</li>
</template>
</my-list>
The inner component has <template>
as well and uses a variant of ngFor like so:
<ul>
<template #items ngFor [ngForOf]="data" [ngForTemplate]="tmpl">
-- insert template here --
</template>
</ul>
The 'tmpl' variable assigned to the ngForTemplate attribute needs to be fetched in the component code:
export class MyListComponent {
@Input() data: any[];
@ContentChild(TemplateRef) tmpl: TemplateRef;
}
@ContentChild and TemplateRef are angular bits, so need to be imported
import { Component, Input, ContentChild, TemplateRef } from '@angular/core';
See the fork of your plunkr with these changes in here plnkr.
This isn't the most satisfactory solution for your stated problem, since you're passing the data in to the list you might as well have the ngFor on the outer. Plus, the additional content (the literal '-- insert template here --') gets dropped, so it you wanted to display that it must be on the outer template as well.
I can see it might be useful where the iteration is provided within the inner component (say from a service call), and maybe to do some manipulation of the template in code.