角管 - 获取当前元素引用

Sta*_*tan 6 angular-pipe angular

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

管道的使用如下,例如<input type="text" value="'my-translation-key' | translate" />

这是实际管道的示例

@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
  }
}
Run Code Online (Sandbox Code Playgroud)

Ank*_*oor 3

根据您的可行性,有两种可能的解决方案:

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

定制管道在哪里

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

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

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

    @ViewChild('inputRef') inputElementRef:ElementRef;

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

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

通过这种方式,您可以轻松工作,但如果单个模板中只有一两个元素,则这种方法会更好,因为获取多个 View Child 将不是干净的代码,尽管它可以正常工作。