需要访问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>

我想检查标记内的文本,在这种情况下为“某些文本”。我似乎无法在指令中访问它。

我应该改为使用组件吗?

佩泽特

您正试图像使用大多数组件一样使用指令。

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

看看这个小问题:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章