2

I have several buttons that are disabled based on what a function returns. How can I reuse the value returned from isDisabled(product) without calling isDisabled(product) for every single button? The calculations within isDisabled() is long so I don't want to have to repeat it.

Currently the code looks like this:

<div *ngFor="let product of prodList">
   <button [disabled]=isDisabled(product)>...</button>
   <button [disabled]=isDisabled(product)>...</button>
   <button [disabled]=isDisabled(product)>...</button>
   <button [disabled]=isDisabled(product)>...</button>
   <button [disabled]=isDisabled(product)>...</button>
</div>
matchi
  • 533
  • 2
  • 6
  • 17

1 Answers1

3

Try wrapping your controls in ng-container with ngIf like:

<div *ngFor="let product of prodList">
  <ng-container *ngIf="{ disabled: isDisabled(product) } as result">
   <button [disabled]="result.disabled">...</button>
   <button [disabled]="result.disabled">...</button>
   <button [disabled]="result.disabled">...</button>
   ...
  </ng-container>
</div>

See also

yurzui
  • 205,937
  • 32
  • 433
  • 399