Konrad Viltersten
Konrad Viltersten

Reputation: 39118

Controlling specific style of the last item of *ngFor

I need to make the last line of controls generated by an iterator both disabled and somewhat invisible. I'm using the following, working, code.

<div *ngFor="let item of data; let last = last;">

  <input class="form-control"
        [value]="item.e"
        [disabled]="last">

  <button (click)="onRemove(item)"
          class="btn btn-outline-danger"
          [style.visibility]="last?'hidden':''">Do</button>

</div>

I'd like to improve the code quality and I'm especially unhappy about the visibility management. When we look at setting disability, it's pretty neat. But the conditional for visibility seems so clunky.

How should the visibility be controlled like-a-boss'ly?

I tested the following, with no luck.

<button (click)="onRemove(item)"
        class="btn btn-outline-danger"
        [style.visibility.hidden]="last">Do</button>

Upvotes: 2

Views: 1429

Answers (2)

ShamPooSham
ShamPooSham

Reputation: 2379

You could do [style.visibility]="last && 'hidden'".

If last is truthy, last && 'hidden' will evaluate to 'hidden', otherwise it will evaluate to whatever falsy value it's set to. When a style is set using the [style.property] syntax, and the value is falsy, it will simply not be set.

Read more about truthy and falsy values here and how you can use short-curcuit logic to evaluate values in a elegant way here .

That said, I think your solution is clean enough and probably more clear for some people (which is important if someone else is going to read your code).

Upvotes: 2

Tal Ohana
Tal Ohana

Reputation: 1138

I would go with creating a class (might be global if used heavily) for invisible item

.invisible {
  visibility: hidden;
}

Then apply the class according to last value

<button (click)="onRemove(item)" 
        class="btn btn-outline-danger"
        [class.invisible]="last">
</button>

Example in this stackblitz

Upvotes: 2

Related Questions