0

I have the following code

<div *ngFor="let item of items">
    <button [disabled]="doSomething(item)"></button>
    <input [someProperty]="doSomething(item)"></div>
    <div [ngClass]="{
          'class1': item.attr == 'val1' || doSomething(item),
          'class2': row.attr != 'val2' && !doSomething(item)
        }"
></div>

in component

doSomething(item) {
    return someBooleanLogic(item);
}

I feel it is not a good practice to recalculate every time the doSomething value for each item in the template.

Is there a more recommended way to do this?

2 Answers 2

1

There are a couple ways around it, one of them being a template "hack":

<div *ngFor="let item of items">
  <ng-container *ngIf="{ something: doSomething(item) } as data">
    <button [disabled]="data.something"></button>
    <input [someProperty]="data.something"></div>
    <div [ngClass]="{
          'class1': item.attr == 'val1' || data.something,
          'class2': row.attr != 'val2' && !data.something
        }"></div>
  </ng-container>
</div>

Another way could be by adding a property to each item object when it is obtained, and read this property.

Sign up to request clarification or add additional context in comments.

Comments

0

If you have a huge amount of items, you can save time by calculating your BooleanLogic before in your Typescript code, save it in a list and loop through it.

1 Comment

Consider adding an example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.