Search code examples
angularangular-pipe

Angular pipe - get current element reference


I want to access the current element where the pipe is being used in. Is it possible in Angular?

Pipe is used as follows e.g. <input type="text" value="'my-translation-key' | translate" />

Here is an example of the actual pipe

@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
  }
}

Solution

  • Two possible solutions based on your feasibility:

    1. Create Template reference variable and send it as param to your custom Pipe.

    Where custom Pipe is

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

    But in this approach, you are getting input element in custom pipe as HTML element which may not fullfill your requirement.

    1. Fetch Input Element as ViewChild in your component then pass it to custom pipe

      @ViewChild('inputRef') inputElementRef:ElementRef;

    In this custom pipe will be :

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

    By this, you can work easily but this approach is better if you have only one or two elements in a single template as fetching multiple View Child won't be a clean code though it'll work fine.