Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap template using ngForTemplate?

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?

like image 845
kulaeff Avatar asked Aug 30 '16 16:08

kulaeff


People also ask

Can you put ngIf on ng-template?

However, note that ng-template is always used along with structural derivatives such as ngIf, nfFor, and ngSwitch. It is used for grouping content that is not rendered, but that can be used in other parts of your code.

What is * ngTemplateOutlet?

ngTemplateOutlet is a powerful tool for creating customisable components. It is used by many Angular libraries to enable users to provide custom templates.

What is pTemplate in ng-template?

pTemplate is a custom-made directive by PrimeNG. Its purpose is to link a template defined by you (the user) to a container defined by the library (PrimeNG). That enables the user to provide a custom template that is displayed inside a component made by the library.


1 Answers

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

like image 198
Günter Zöchbauer Avatar answered Sep 18 '22 12:09

Günter Zöchbauer