Haris Bašić Haris Bašić - 3 years ago 220
Javascript Question

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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download