Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of * in *ngFor in angular2?

Tags:

angular

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> 
like image 707
Vikram Babu Nagineni Avatar asked Feb 19 '16 06:02

Vikram Babu Nagineni


People also ask

Why are using * In ngFor in Angular?

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.

What is mean * ngFor in Angular?

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.

Can we use * ngIf and * ngFor on single line?

In Angular, we cannot use two structural directives on the same element. i.e., we cannot place *ngFor,*ngIf together on same element.

What is an ngFor in a tag?

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.


2 Answers

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.

like image 185
Günter Zöchbauer Avatar answered Sep 21 '22 20:09

Günter Zöchbauer


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> 
like image 23
K Ling Avatar answered Sep 21 '22 20:09

K Ling