As per my understanding, Both are doing the same functions. But,
ngFor
would be works like as collections?.
ngForOf
would be works like as generics?.
Is my understanding is correct? or Could you please share more difference's(details) about
ngFor
andngForOf
?
Descriptionlink. The ngForOf directive is generally used in the shorthand form *ngFor . In this form, the template to be rendered for each iteration is the content of an anchor element containing the directive. The following example shows the shorthand syntax with some options, contained in an <li> element.
When we use *ngFor , we're telling Angular to essentially treat the element the * is bound to as a template. Angular's <ng-template> element is not a true Web Component (unlike <template> ).
NgIf conditionally displays items by adding or removing them from the DOM depending on the condition. NgFor renders a list of items from iterable objects.
To Use ngFor directive, you have to create a block of HTML elements, which can display a single item of the items collection. After that you can use the ngFor directive to tell angular to repeat that block of HTML elements for each item in the list.
ngFor
and ngForOf
are not two distinct things - they are actually the selectors of the NgForOf directive.
If you examine the source, you'll see that the NgForOf directive has as its selector: [ngFor][ngForOf]
, meaning that both attributes need to be present on an element for the directive to 'activate' so to speak.
When you use *ngFor
, the Angular compiler de-sugars that syntax into its cannonical form which has both attributes on the element.
So,
<div *ngFor="let item of items"></div>
desugars to:
<template [ngFor]="let item of items"> <div></div> </template>
This first de-sugaring is due to the '*'. The next de-sugaring is because of the micro syntax: "let item of items". The Angular compiler de-sugars that to:
<template ngFor let-item="$implicit" [ngForOf]="items"> <div>...</div> </template>
(where you can think of $implicit as an internal variable that the directive uses to refer to the current item in the iteration).
In its canonical form, the ngFor attribute is just a marker, while the ngForOf attribute is actually an input to the directive that points to the the list of things you want to iterate over.
You can check out the Angular microsyntax guide to learn more.
ngFor
is a structural directive of Angular which replaces the ng-repeat
attribute of AngularJS
You can use ngFor
as a shorthand
<li *ngFor="let item of items">{{item.name}}</li>
or as the longhand version
<template ngFor let-item="$implicit" [ngForOf]="items"> {{item.name}} </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