I\'m trying to create a component that accepts multiple templates as inputs. This is the example I have:
@Component({
selector: \'data-list\',
styles
I solved this same issue by using the string selector available to the ContentChild decorator.
You will need to specify template variables when using your data-list component:
<data-list [itemsData]="data">
<ng-template #firstItemTemplate let-item>
<h1 style="color:red;">{{ item.header }}</h1>
<div>{{ item.content }}</div>
</ng-template>
<ng-template #standardTemplate let-item>
<h1>{{ item.header }}</h1>
<div>{{ item.content }}</div>
</ng-template>
</data-list>
Then, inside your data-list component class, assign the template variables to local variables on the component:
@Input() itemsData: any[];
@ContentChild('firstItemTemplate') firstItemTemplate: TemplateRef<ElementRef>;
@ContentChild('standardTemplate') standardTemplate: TemplateRef<ElementRef>;
After this, you'll be able to render the passed-in templates from your data-list component.
@Component({
selector: 'data-list',
styles: [
require('./data-list.component.scss')
],
template: `
<span *ngFor="let item of itemsData; let i = index" >
<ng-template *ngIf="i == 0; else nextTmpl"
ngFor let-item [ngForOf]="[item]" [ngForTemplate]="firstItemTemplate"
></ng-template>
<ng-template #nextTmpl
ngFor let-item [ngForOf]="[item]" [ngForTemplate]="standardTemplate"
></ng-template>
</span>
`
})
Try this instead.
@Component({
selector: 'data-list',
styles: [
require('./data-list.component.scss')
],
template: `
<ng-template ngFor [ngForOf]="itemsData" [ngForTemplate]="itemTemplate"></ng-template>
`
})
export class DataListComponent {
@Input() itemsData: any[];
@ContentChild(TemplateRef) itemTemplate: TemplateRef<ElementRef>;
}