Difference between *ngFor vs @for in......

Difference between *ngFor vs @for in Angular 17

Difference between *ngFor vs @for in Angular 17

Difference between *ngFor vs @for in Angular 17



Been trying to upgrade and migrate some of my angular projects into Angular 17. Also still learning the standalone component as part of the major upgrade of the said version.One thing I noticed is the documentation is they are using now the @for eg.


@for (car of cars; track car) {
   <option [value]="car.value">{{car.viewValue}}</option>
}

instead of *ngFor

<option *ngFor="let car of cars" [value]="car.value">{{car.viewValue}}</option>


To be honest, I’m still liking the *ngFor.Any difference between these two or is @for is the new *ngFor? If that so, any particular reason are they doing that? *ngFor is much simpler and can be one liner.


Solution


The @for block is part of the new control flow syntax introduced in Angular 17.0The control flow blocks (@if@for@switch) are here to replace the 3 structural directives ngIfngFor and ngSwitch.In the case of the @for block, feature wise they serve the same purpse with a few advantages :


  • No need to import the directive in standalone componentsGenerate a bit less code in the final bundleenable better DX for track by passing a key directly.Make devs more concious about the track functionality by making it required.Nice DX for empty for-loops with the @empty block



Share Article:
  • Facebook
  • Instagram
  • LinkedIn
  • Twitter
  • Recent Posts