可以在 Javascript 或 Typescript 中使用 Pipes 吗?

Can Pipes be used in Javascript or Typescript?

这是一个天真的问题,但我已经思考了几个小时了。

可以从 JavaScript/TypeScript 调用管道吗?还是它们只能在 templates 中使用?我看过的所有参考资料和 tutorials 都显示管道仅在模板中使用。

我对此没有困难的用例,但我正在研究 Angular2 的各种元素,可以想象我可能需要直接使用 Pipe 而不是在 JS/TS

是的,管道只是代码,因此您可以将其用作代码而无需在模板中使用它。例如,我有一个过滤产品列表的 ProductFilterPipe。我们可以在代码中使用该管道,如下所示:

filterProducts() : void {
    let productFilterPipe = new ProductFilterPipe();
    let filteredList = productFilterPipe.transform(this.products, "am");
    console.log(filteredList);
}

所以这是可能的。

您还可以通过导入使用默认 Angular 管道(例如 DecimalPipe、CurrencyPipe):

import {DecimalPipe} from '@angular/common';

然后

使用它
DecimalPipe.prototype.transform(value, formattingString)