需要访问 Angular 5 指令文本



>我正在尝试创建一个自定义指令来替换自定义指令的内部文本。 我似乎无法访问内部文本内容来应用某些逻辑。

代码如下:

import { Directive, ElementRef, Renderer2, ViewContainerRef } from '@angular/core';
@Directive({
  selector: 'text-transformer'
})
export class TextTransformerDirective {
  constructor(
    private elem: ElementRef) {
      // need access to inner text before setting new text
      // elem.nativeElement.outerHTML, innerHTML, outerText, innerText are all empty at this point
      elem.nativeElement.outerHTML = '<span>My new Text</span>';
  }
}

用法:

<text-transformer>Some text</text-transformer>

我想检查标签中的文本,在本例中为"一些文本"。 我似乎无法在指令中访问它。

我应该改用组件吗?

您正在尝试使用指令,就像大多数人使用组件一样。

但是,要转换文本,它是您想要的指令。只需更改您的选择器即可。

看看这个 plunk:

https://plnkr.co/edit/C3SR92TVN1x5bgSazWNW?p=preview

import {Directive, ElementRef, OnInit} from '@angular/core'
@Directive({
  selector: '[text-transformer]'
})
export class TextTransformerDirective implements ngOnInit {
    constructor(
    private elem: ElementRef) {
      // need access to inner text before setting new text
      // elem.nativeElement.outerHTML, innerHTML, outerText, innerText are all empty at this point
    }
  ngOnInit() {
    console.log(this.elem.nativeElement.innerText);
    this.elem.nativeElement.innerText += ' !!My new Text!!';
    console.log(this.elem.nativeElement.innerText) 
  }
}

然后从任何其他组件使用该指令,如下所示:

<h1 text-transformer>This text will be changed</h1>

并供参考:https://angular.io/guide/attribute-directives

最新更新