Haris Bašić
Haris Bašić

Reputation: 1383

Rendering <ng-content> in angular 2 more times

I have code like this

<template *ngIf='mobile'>
  <div class='wrapper'>
    <div class='nav'>
        <ng-content></ng-content>
    </div>
  </div>
</template>

<template *ngIf='desktop'>
  <ng-content></ng-content>
</template>

However, Angular 2 renders ng-content just one time. Is there a way to get this case working properly without too much hacking?

Upvotes: 8

Views: 2021

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657108

update Angular 5

ngOutletContext was renamed to ngTemplateOutletContext

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

original

You can pass the content as a template, then you can render it multiple times.

<parent>
 <template>
  projected content here
 </template>
</parent>

In parent

<ng-container *ngIf='mobile'>
  <div class='wrapper'>
    <div class='nav'>
        <template [ngTemplateOutlet]="templateRef"></template>
    </div>
  </div>
</ng-container>

<template *ngIf='desktop'>
  <template [ngTemplateOutlet]="templateRef"></template>
</template>

export class ParentComponent {
  constructor(private templateRef:TemplateRef){}
}

You can also pass data to the template to bind with the projected content.

<ng-container *ngIf='mobile'>
  <div class='wrapper'>
    <div class='nav'>
        <template [ngTemplateOutlet]="templateRef" [ntOutletContext]="{ $implicit: data}"></template>
    </div>
  </div>
</ng-container>

<ng-container *ngIf='desktop'>
  <template [ngTemplateOutlet]="templateRef" [ntOutletContext]="{ $implicit: data}"></template>
</ng-container>

export class ParentComponent {
  @Input() data;

  constructor(private templateRef:TemplateRef){}
}

and then use it like

<parent [data]="data">
 <template let-item>
  projected content here {{item}}
 </template>
</parent>

See also My own Angular 2 Table component - 2 way data binding

Upvotes: 3

Related Questions