获取Angular2指令中字符串插值后的内容

获取Angular2指令中字符串插值后的内容,angular,Angular,使用Angular2.x 假设我有以下标记: <p myCustomDirective>{{someVar}}</p> {{someVar} 如何从指令生命周期挂钩之一中访问{{someVar}}的渲染/插值?我希望能够在指令代码中引用和使用“someVar”的值。最简单的方法可能是将ElementRef注入指令,并从其nativeElement属性读取值: @Directive({ selector: '[myCustomDirective]' }) expor

使用Angular2.x

假设我有以下标记:

<p myCustomDirective>{{someVar}}</p>

{{someVar}


如何从指令生命周期挂钩之一中访问{{someVar}}的渲染/插值?我希望能够在指令代码中引用和使用“someVar”的值。

最简单的方法可能是将
ElementRef
注入指令,并从其
nativeElement
属性读取值:

@Directive({
  selector: '[myCustomDirective]'
})
export class MyCustomDirective {
  constructor(private elRef: ElementRef) { }

  ngAfterViewInit() {
    console.log(this.elRef.nativeElement.textContent);
  }
}

完美!ngAfterViewInit+textContent似乎是我找不到的神奇酱汁。