角管 - 获取当前元素参考

时间:2017-11-28 18:40:23

标签: angular angular-pipe

我想访问正在使用管道的当前元素。是否可以在Angular中使用?

管道如下使用,例如@Pipe({ name: 'translate', pure: false }) export class TranslatePipe implements PipeTransform { transform(key: string, params?: ITranslationSelector): string { // 1. Get the value by key // 2. Return the value // What I want as well: // this.el.nativeElement.dataset.translationKey = key; // Where el is current element where pipe is used } }

以下是实际管道的示例

{{1}}

3 个答案:

答案 0 :(得分:2)

基于您的可行性的两种可能的解决方案:

  1. 创建模板引用变量并将其作为参数发送到自定义管道。
  2. 自定义管道

    的位置
    export class CustomPipe implements PipeTransform {
        transform(key: string, params: any): string {
            //Here param is your input element
            return 'your_value';
        }
    

    但是在这种方法中,您将自定义管道中的输入元素作为HTML元素获取,这可能无法满足您的要求。

    1. 在组件中将输入元素作为ViewChild获取,然后将其传递给自定义管道

      @ViewChild('inputRef')inputElementRef:ElementRef;

    2. 在这个自定义管道中将是:

      export class CustomPipe implements PipeTransform {
              transform(key: string, params: any): string {
                  //Here param is your input element
                  return 'your_value';
              }
      

      通过这种方式,您可以轻松地工作,但是如果您在单个模板中只有一个或两个元素来获取多个View,那么这种方法会更好。虽然它可以正常工作,但它不是一个干净的代码。

答案 1 :(得分:0)

您还可以使用模板引用变量。 模板:

<input #inputEl type="text" value="'my-translation-key' | translate:inputVariable" />

Pipe ts文件的一部分:

export class TranslatePipe implements PipeTransform {
    transform(key: string, element?: any): string {
        // Element was marked by #inputEl template variable.
        element.dataset.translationKey = key;
   }
}

答案 2 :(得分:0)

我想分享一些尝试,这些尝试并没有使我找到所需的解决方案,但是可能会导致其他人使它起作用。还有一个尚未提及的想法。


进入模板管道

另一种方法可能是挂接到模板中以创建角度管道。

想法:获取AST并检查管道类,并注入元素的引用并将其作为参数放入(如之前其他人所提到的)。

例如,像这些家伙那样的人:https://github.com/typebytes/ngx-template-streams


尝试:

对于pure: true,每个组件仅创建一个实例管道类。

pure: false中,组件HTML中每次使用管道都会创建一个实例管道类。

您可以在管道的构造函数中注入elementRef: ElementRef,但是(在两种情况下)您只会获得对使用管道的组件的引用。

我想也许可以通过将另一个指令注入到引用HTMLElement的管道中以某种方式工作。

示例:

<my-component>
    <div>{{'foo' | mypipe}}</div>
    <div>{{'foo' | mypipe}}</div>
    <input type="text" [value]="'bar' | mypipe">
    <input type="text" [value]="'bar' | mypipe">
</my-component>

我试图创建一条指令以获取常见HTMLElement的引用,该外观如下所示:

@Directive({
    selector: 'input,div,span'
})
export class ElementRefDirective {
    constructor(public readonly elementRef: ElementRef) {}
}

但是我无法将其注入MyPipe类中,也无法将其注入(将MyPipe注入指令中)。