angularangular18

How to use @for with NgClass in angular 18


I have the following HTML structure in my template:

<tbody>
    @for(element of elements.value; track $index; let idx = $index, let isEven = $even){
       <tr *ngClass="isEven ? 'some styles here' : 'some other styles otherwise' ">
       <tr>
    }
<tbody>

The problem is in this case I'm getting the following error:

Property 'isEven' does not exist on type 'MyCoomponentName'

Could someone explain how to use this new @for with the ngClass? My main goal is to paint even <tr> of one color and odds of another, maybe there is another way to do it but not sure.

I tried *ngClass={{isEven ? '' : ''}} but didn't worked but not sure that's even possible.


Solution

  • You should follow the same syntax that is mentioned in the documentation.

    Contextual variables in @for blocks

    The ngClass directive is designed for property binding and usually is not a structural directive (has the suffix * to it). so replace it with [ngClass].

    The ngClass is designed for conditionally adding classes, if you want to conditionally add styles, you should prefer [ngStyle] instead.

    <table>
      <tbody>
          @for(element of elements.value; track element.id; let idx = $index, isEven = $even){
            <tr [ngClass]="isEven ? 'red' : 'yellow' ">
              <td>{{element.value}}</td>
            <tr>
          }
      <tbody>
    </table>
    

    Full Code:

    import { Component } from '@angular/core';
    import { bootstrapApplication } from '@angular/platform-browser';
    import { CommonModule } from '@angular/common';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [CommonModule],
      styles: [
        `
      .red {
        background-color: red;
      }
      .yellow {
        background-color: yellow;
      }
      `,
      ],
      template: `
        <table>
          <tbody>
              @for(element of elements.value; track element.id; let idx = $index, isEven = $even){
                <tr [ngClass]="isEven ? 'red' : 'yellow' ">
                  <td>{{element.value}}</td>
                <tr>
              }
          <tbody>
        </table>
      `,
    })
    export class App {
      name = 'Angular';
      elements = {
        value: [
          { id: 1, value: 'one' },
          { id: 2, value: 'two' },
          { id: 3, value: 'three' },
        ],
      };
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo