How can I repeat a piece of HTML multiple times without ngFor and without another @Component?

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

The recently added ngTemplateOutlet might be what you want

<template [ngTemplateOutlet]="templateRefExpression" [ngOutletContext]="objectExpression"></template>

It can currently be used like

<template #templateRef>
    <pre>{{self | json }}</pre>
</template>

<template [ngTemplateOutlet]="templateRef"></template>

A template can also be passed to a child component to be rendered there

@Component({
  selector: 'some-child',
  providers: [],
  template: `
    <div>
      <h2>Child</h2>
<template [ngTemplateOutlet]="template" ></template>
<template [ngTemplateOutlet]="template" ></template>
    </div>
  `,
  directives: []
})
export class Child {
  @ContentChild(TemplateRef) template:TemplateRef;
}

to be used like

<some-child>
  <template>
    <pre>{{self | json }}</pre>
  </template>
</some-child>

stackblitz example

Another Plunker example
that uses data passed as

<template [ngTemplateOutlet]="..." [ngOutletContext]="templateData"

This way ngOutletContext can be used in the template like

<template let-image="image">
 {{image}}

where image is a property of templateData

If $implicit is used

<template [ngTemplateOutlet]="..." [ngOutletContext]="{$implicit: templateData}"

the ngOutletContext can be used in the template like

<template let-item>
 {{item}}

Leave a Comment