我需要知道哪个组件调用了我的管道。
我不想将组件作为管道的参数,例如这个
{{ “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/