1

I have a fairly straightforward use-case; a tabular list of users, each of whom might be active or not. Depending on which it is, the row is styled differently. The conditional style is applied in more than one place:

<tr *ngFor="let user of users" [ngClass]="{'not-active': user.status !== 'ACT'}">
<td>{{user.username}}</td>
<td>{{user.status}}</td>
<td>
  <button [disabled]="user.status !== 'ACT'">Edit</button>
  <button [disabled]="user.status === 'ACT'">Activate</button></a>
</td>

Obviously, this is not very good since I have to spell out my conditional logic three times. It would be much nicer if I could write:

<tr *ngFor="let user of users; let isActive = user.status === 'ACT';"
        [ngClass]="{'not-active': !isActive}">
<td>{{user.username}}</td>
<td>{{user.status}}</td>
<td>
  <button [disabled]="!isActive">Edit</button>
  <button [disabled]="isActive">Activate</button></a>
</td>

However, I understand from reading this post and others that this is currently not possible.

The proposed workaround from the post above is to create a component that contains an HTML template (for the table row?) and then to do the logic in the component class. This seems quite an overhead for a relatively simple requirement...

So before diving in, I'd like to ask if this is truly the canonical solution to this type of problem?

In response to a comment, I have implemented a simple example of the issue on stackblitz (I've not used this before... can you see my codebase?).

Oscar Bravo
  • 250
  • 4
  • 11

1 Answers1

1

Edit: The answer is no, U can't declare a scope variable within a *nfFor

The only way I think u can achieve that is by wrapping the tr content into something and using a *ngIf. Something like:

<tr *ngFor="let user of users">
    <div *ngIf="user.status === 'ACT'; let isActive" [ngClass]="{'not-active': !isActive}">

      <td>{{user.username}}</td>
     <td>{{user.status}}</td>
     <td>
        <button [disabled]="!isActive">Edit</button>
         <button [disabled]="isActive">Activate</button></a>
     </td>
</div>

(I can't close the tr tag)

But by using on this way you aren't going to aply the not-active class to the table row, but to the inside div

Lazaro Henrique
  • 527
  • 5
  • 7
  • Thanks for your reply - this is a good solution when dealing with
    and
  • but, you're right, it messes up table tags. Hopefully this (rather obvious) use-case will be introduced in some future upgrade.
– Oscar Bravo May 30 '18 at 09:04