【问题标题】:angular - declare result of pipe as local variable角度 - 将管道的结果声明为局部变量
【发布时间】:2018-11-09 13:38:48
【问题描述】:

我在标签中使用了 ngx-pipe 的百分比管道两次。一次确定哪个颜色类别(成功或信息),一次显示百分比。

<label class="label" [ngClass]="(item.amount |
percentage:item.total) >= 100 ? 'label-success' : 'label-info'">Progress {{item.amount | percentage:item.total:true}}%</label>

有没有一种方法可以将该管道的结果存储为本地模板变量一次,就像

<label class="label" #percent="(item.amount |
percentage:item.total)" [ngClass]="percent >= 100 ? 'label-success' : 'label-info'">Progress {{percent}}%</label>

我知道你可以将它存储在 *ngIf 或 *ngFor 指令中,例如

<div *ngIf="item$ | async as item">

<div *ngIf="item$ | async; let item">

我的问题有类似的方法吗?

【问题讨论】:

  • 如果 ng-container 不会添加额外的 html,为什么还需要其他方式?
  • 嗯,你给了自己一个面向模板的解决方案的答案。否则,请知道管道只是类实例。这意味着您可以在组件的逻辑中创建它们的实例。我将您重定向到我之前关于日期管道的类似问题的答案之一:stackoverflow.com/questions/48183677/….
  • @trichetriche 是否可以像在日期管道的答案中那样使用异步管道??
  • @malbarmawi 是的,the source code of the pipe 只需要更改检测器参考。但我不会使用它,myslef,我更喜欢手动使用 RxJS 并将我的异步管道保留到我的模板!

标签: angular angular-template angular-pipe angular-template-variable


【解决方案1】:

AFAIK 现在不可能写到运行时计算绑定的别名(* ngFor with pipe 是例外),但你可以做的是。创建一个 function/Pure pipe 并将 memoization 应用于该函数,以便减少计算量。

<label class="label" 
  [ngClass]="getPercentage(item) >= 100 ? 'label-success' : 'label-info'">
     Progress {{getPercentage(item)}}%
</label>

组件

calculation: any = {};
percentage = new PercentPipe();
// below function can be stay as pure Pipe as well.
getPercentage (item) {
   let key = `${item.amount}-${item.total}`
   if(!calculate[key]) calculate[key] = percentage.transform(item.amount, item.total, true);
   return calculate[key];
}

通过这个解决方案,我们计算了一次价值并在其他地方使用它。但不在模板变量中,而是在组件中记住上次计算的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多