Search code examples
htmlangular

Convert ngFor to @for in angular


i'm currently trying to adapt my code to use the new features of angular 17, but i've got a problem with converting some stuff in the html.

So i have this field that retrieves the nationalities and sets the value to them

<mat-form-field>
        <mat-label>Nationality</mat-label>
        <mat-select formControlName="nationality">
            <mat-option *ngFor="let nationality of nationalities" [value]="nationality">
                {{ nationality }}
              </mat-option>
        </mat-select>
</mat-form-field>

And this is a snippet of how i've had it before

<mat-option value="English">English</mat-option>
<mat-option value="German">German</mat-option>
<mat-option value="Spanish">Spanish</mat-option>
<mat-option value="Italian">Italian</mat-option>
<mat-option value="French">French</mat-option>

But i can't find a way so i can use @for instead of ngFor. I'm new to angular so, sorry if the question is stupid. Thank you!


Solution

  • The new syntax is not that hard. Here's how you can use the new syntax instead of the old one:

    <mat-form-field>
      <mat-label>Nationality</mat-label>
      <mat-select formControlName="nationality">
        @for (nationality of nationalities; track nationality) {
          <mat-option [value]="nationality">
            {{ nationality }}
          </mat-option>
        }
        <!-- you could add @empty if needed -->
      </mat-select>
    </mat-form-field>
    

    I strongly suggest you read the documentation about it here: angular.dev Documentation