skip to Main Content

I have a table in which I want to give background color to some rows. The condition is that if the first data element of the row (which is going to be an icon) is archived icon, then I have to give the whole row a gray background color.
The HTML code is as:

<tr class='flow-row' [bSelectableRow]="item">
  <td>
    <ng-container *ngFor='let icon of getIconForFlow(item);'>
      <class='flow-icon' [icon]="icon.icon" [title]="icon.title">
        </bt-icon>
    </ng-container>
  </td>
  <td> Name </td>
</tr>

I tried something like this:

<tr class='flow-row' [bSelectableRow]="item">
  <td>
    <ng-container *ngFor='let icon of getIconForFlow(item);'>
      <class='flow-icon' [icon]="icon.icon" [title]="icon.title">
        </bt-icon>
    </ng-container>
  </td>
  <td> Name </td>
</tr>

But I am getting a parser error with this: Bindings cannot contain assignments.
Same was the error if I tried giving ngClass instead of ngStyle.

Is there a fix for this?

2

Answers


  1. Angular has issues when the template contains some functions. You can create a method in your .ts file that returns a value for the background color. Replace it with getIconForFlow(item).some(icon => icon.icon === 'archived') ? '#ccc' : '' in your template.

    Login or Signup to reply.
  2. Here’s an example of how you can achieve this:

    In your component.ts file:

    getRowStyle(item) {
      if (this.getIconForFlow(item)[0].icon === 'archived-icon') {
        return {'background-color': 'gray'};
      }
    }
    

    In your component.html file:

    <tr class='flow-row' [bSelectableRow]="item" [ngStyle]="getRowStyle(item)">
      <td>
        <ng-container *ngFor='let icon of getIconForFlow(item);'>
          <class='flow-icon' [icon]="icon.icon" [title]="icon.title">
            </bt-icon>
        </ng-container>
      </td>
      <td> Name </td>
    </tr>
    

    method getRowStyle in the component class that takes an item as an argument and returns a style object containing the background color if the first icon of the row is an archived icon. Then, in the HTML template, we use the [ngStyle] directive to apply this style to the row.

    I hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search