9

I cannot find a good description of the differences anywhere. Same with *ngIf and ngIf

An example of *ngFor

<li *ngFor="let video of page" ...>
  <img src="api/Videos/{{video.id}}/thumbnail">
</li>

and an example of ngFor

<template ngFor let-labelid [ngForOf]="labelLookup | keyValueFilter" >
  <label  [ngStyle]="{'background-color': labelLookup[labelid].color}">
    <input (click)="changeLabel(labelid)" type="radio" name="labelSelector" value="{{ labelid }}" [checked]="labelid == 1">
  </label>
</template>
Rob
  • 14,746
  • 28
  • 47
  • 65
Brian Leach
  • 3,974
  • 8
  • 36
  • 75
  • 1
    `*ngFor` is shorthand of `ngFor` with `template`, you can find the same on angular docs & teropa blog [here](https://teropa.info/blog/2016/03/06/writing-an-angular-2-template-directive.html) – Pankaj Parkar Oct 20 '16 at 16:38

1 Answers1

8

The difference is that *ngFor is converted to <template ngFor [ngForOf]="..." internally.

They are equivalent but the former is more convenient to write.

The explicit version (<template ngFor ...>) allows to apply the directive to multiple elements at once while the implicit version (shorthand) only wraps the element where it is applied to with the <template> tag.

With Angular 2.0.0 final the <ng-container> element was added that allows to use the shorthand syntax on an element that behaves like the <template> element (is not added to the DOM).

See also

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567