angular 2 get组件调用管道

标签 angular typescript

我需要知道哪个组件调用了我的管道。

我不想将组件作为管道的参数,例如这个 {{ “textArg” | myTranslatorPipe:thisTemplate }}.

我想要这个 {{ "textArg"| myTranslatorPipe }} 并仍然访问该组件。

export class myTranslatorPipe implements PipeTransform {
    transform(value: string): string {
        //get component here ?
    }   
}

我将如何做到这一点? 提前致谢!

最佳答案

我发现这样做的唯一方法是直接将组件作为参数传递给管道。

transform 方法在 args 中接收无限数量的参数,下面的代码将实现这一点:

export class myTranslatorPipe implements PipeTransform {
    transform(value: string, componentRef: any): string {
        //component is stored inside the 'componentRef' 
        if (typeof componentRef === 'undefined' || componentRef === null) {
            throw Error('Missing "componentRef" parameter, correct implementation is "myTranslatorPipe: this".');
        }
        // here you can use your component reference
    }   
}

唯一的问题是你必须以这种方式实现你的管道 {{ "textArg"| myTranslatorPipe: this}} 而不仅仅是 {{ "textArg"|我的翻译管道}}

验证不是强制性的:typeof componentRef === 'undefined' || componentRef === null

关于angular 2 get组件调用管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39804257/

相关文章:

Angular 2 : How to read a lazy-loaded Module's routes from within a Component

javascript - 选择不使用 Angular 2 绑定(bind)动态更新的选项

javascript - 从刷新的 JSON 更新 img src

angular - NoUiSlider - 如何自定义我的 pips 标签以具有字符串值?

带有 ngx-codemirror 的 Angular 8

angular - 如果缺少 key 或正在加载翻译文件,则 ngx-translate 默认文本

angularjs - 在 Typescript 中使用 AngularJS Controller 的范围

javascript - 如何从父方法创建子类型的新对象

reactjs - 在 React 中制作包装器组件

angular - @types/webrtc 的 typescript 错误