What is the meaning of * before ngFor in following sample and why it is needed?
<div *ngFor="#hero of heroes" (click)="selectHero(hero)"> {{hero.name}} </div>
The *ngFor directive is used to repeat a portion of HTML template once per each item from an iterable list (Collection). The ngFor is an Angular structural directive and is similar to ngRepeat in AngularJS. Some local variables like Index, First, Last, odd and even are exported by *ngFor directive.
NgFor is a built-in template directive that makes it easy to iterate over something like an array or an object and create a template for each item.
In Angular, we cannot use two structural directives on the same element. i.e., we cannot place *ngFor,*ngIf together on same element.
The ngFor directive does create the HTML-Element it is placed in as many times as there are elements in the array. So to create a list-element for each array element, we place the ngFor directive inside of the li tag. example.component.html.
ngFor
can only be applied to a <template>
. *ngFor
is the short form that can be applied to any element and the <template>
element is created implicitly behind the scene.
https://angular.io/api/common/NgForOf
Syntax
<li *ngFor="let item of items; let i = index">...</li>
<li template="ngFor let item of items; let i = index">...</li>
<template ngFor let-item [ngForOf]="items" let-i="index"><li>...</li>
It's the same pattern for all structural directives
Plunker example
update
With the 2.0.0 final release <ng-container>
was introduced, that behaves like <template>
(a wrapper element that isn't actually added to the DOM) but supports the *ngFor="..."
syntax.
When Angular sees the asterisk (*) in ngFor, it will use its DOM element as template to render the loop.
<div *ngFor="#hero of heroes"> {{ hero.name }} </div>
is equivalent to
<template ngFor #hero [ngForOf]="heroes"> <div> {{ hero.name }} </div> </template>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With