如何在Angular 2的组件中使用管道? [英] How to use a pipe in a component in Angular 2?

查看:56
本文介绍了如何在Angular 2的组件中使用管道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个管道类,它根据您传递的参数返回数据.我知道如何使用|符号在模板HTML中使用它,但是我也想在组件中使用它.

I have a pipe class which returns data based on the arguments you are passing. I know how to use it in my template HTML using the | symbol, but I want to use it in my component too.

有没有一种方法可以直接从Angular 2的组件或服务内部调用管道?

Is there a way to call a pipe directly from inside a component or a service in Angular 2?

推荐答案

您可以使用以下代码直接在代码中调用管道:

You can call your pipe directly in your code by using:

YourPipeClass.prototype.transform(value, arg1, arg2);

您可以从组件内部或导入它的任何其他位置调用它.

You can call it from inside your component or from anywhere else that imports it.

还有new方式:

new SortTodosPipe().transform(value, arg1, arg2);

但是请记住,它将创建一个对象,因此请保存该对象以备后用或使用prototype方法.

But keep in mind it will create an object, so either save that object for later use or use the prototype method.

无论如何,如果要在组件中使用管道,必须将管道添加到providers中,例如:

Anyway you choose, you must add the pipe to your providers if you use it inside a component, like so:

@NgModule({
    providers: [YourPipe]
})

这篇关于如何在Angular 2的组件中使用管道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆