7

I try to make ListView component using ngForTemplate for custom templates

list-view.component.html

<div class="list-view">
    <template ngFor [ngForOf]="items" [ngForTemplate]="template">
    </template>
</div>

list-view.component.ts

@Component({
    selector: 'm-list-view',
    styleUrls: ['./list-view.component.less'],
    templateUrl: './list-view.component.html'
})

export class ListViewComponent {
    @Input() items: any[] = [];

    @ContentChild(TemplateRef)
    template: any;
}

When I use it like this:

<m-list-view [items]="categories">
    <template let-item="$implicit">
        **some HTML markup**
    </template>
</m-list-view>

the resulting is:

<m-list-view>
    <div class="list-view">
        **some HTML markup**
        **some HTML markup**
        **some HTML markup**
        ...
    </div>
</m-list-view>

but I need this:

<m-list-view>
    <div class="list-view">
        <div class="list-view-item">**some HTML markup**</div>
        <div class="list-view-item">**some HTML markup**</div>
        <div class="list-view-item">**some HTML markup**</div>
        ...
    </div>
</m-list-view>

What should I do to wrap each list view item template in div.list-view-item?

kulaeff
  • 453
  • 3
  • 12

1 Answers1

11

update Angular 5

ngOutletContext was renamed to ngTemplateOutletContext

It is now advised that you use the following syntax:

<div class="list-view">
  <div class="list-view-item" *ngFor="let item of items">
    <ng-container *ngTemplateOutlet="template; context: item">
    </ng-container>
  </div>
</div>

See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

original

<div class="list-view">
  <div class="list-view-item" *ngFor="let item of items">
    <template [ngTemplateOutlet]="template" [ngOutletContext]="item"></template>
  </div>
</div>

See also https://angular.io/docs/ts/latest/api/common/index/NgTemplateOutlet-directive.html

Trent
  • 4,208
  • 5
  • 24
  • 46
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thanks for your reply, but it's not what I was asking for. I need template to be wrapped in `div.list-view-item` within `ListViewComponent`, without specifying it manually. In other words, it should be done by `ListViewComponent` itself. – kulaeff Aug 30 '16 at 21:58
  • Now I'm getting the error: _TypeError: Cannot read property 'title' of undefined_. `` – kulaeff Aug 31 '16 at 08:39
  • 1
    I changed `$implicit` to `{ item: item }` and now it works as expected! – kulaeff Aug 31 '16 at 10:04
  • Then you would not need to change $implicit: `
    `
    – Stefan Rein Jul 30 '18 at 09:23