Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't *ngFor need brackets?

I am new to the Angular framework, and have recently been introduced to the attribute *ngFor="".

As I have learned, this takes the same parameters as an JavaScript for() loop... And therefore, *ngFor="let item of itemCollection". But, in contrast to other directives, *ngFor does not require [] around it to be treated as code.

This documentation page suggests that the hero attribute needs [] around it for the value to be treated as code, and returning the value of "hero":

<app-hero-detail *ngFor="let hero of heroes" [hero]="hero"></app-hero-detail>

Why is it so? The *ngFor is also evaluated, but does not need the [] obviously... Is it the * prefix that indicates that the value must always be treated as code or what?

like image 866
William R. Avatar asked Mar 04 '23 20:03

William R.


1 Answers

To begin you must first understand that the bracket notation []is used for property binding in Angular.

I will use the example code you provided to help explain this:

<app-hero-detail *ngFor="let hero of heroes" [hero]="hero"></app-hero-detail>

In this case the [hero] in [hero]="hero" is an example of property binding in which the data will flow one-way from data source (the component) to the view (the HTML). The property hero you will find was defined as in input property of that component using the @Input decorator.

Which brings us to your question:

Why doesn't *ngFor need brackets?

The answer is exactly what you thought. You do not need to use [bracket notation] for the *ngFor because of the existence of the asterisk (*). The asterisk is Angular short hand notation (or syntatical sugar) that allows developers to write cleaner, easier to understand and maintain code. Beneath the sheets, when the Angular compiler "desugars" your code it will turn out looking something like this:

<template [ngFor]="let hero of heroes">
     <div></div>
 </template>

From there the Angular compiler will further "desugar" your code to something like this:

<template ngFor let-hero="$implicit" [ngForOf]="heros">
   <div>...</div>
 </template>

So in conclusion you can see that ngFor Structural Directive ultimately is treated like any other property that requires property binding. However, on account of it being a built in directive Angular provided us with a much cleaner to use shorthand notation. Unlike the hero property which we created and defined ourselves, therfore requiring us to use the bracket notation explicitly in the HTML. Don't forget even though you can use the bracket notation with structural directives you should always prefer the asterisk.

like image 163
Narm Avatar answered Mar 09 '23 01:03

Narm