简体   繁体   中英

How to create an angular template variable

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM