【问题标题】:Need access to Angular 5 directive text需要访问 Angular 5 指令文本
【发布时间】:2018-08-29 16:26:42
【问题描述】:

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

代码如下:

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>

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

我应该改用组件吗?

【问题讨论】:

  • 为什么不把它改成组件并测试一下呢?
  • 有性能差异吗?
  • 否,但无论如何您都在尝试将此指令用作组件。
  • 可能,我正在从 AngularJs(预组件)迁移到 Angular,所以组件在当前应用程序中是一个较新的概念。
  • 要访问元素的文本,最好使用管道而不是指令,请参阅this

标签: angular innerhtml directive innertext elementref


【解决方案1】:

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

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

看看这个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

【讨论】:

  • 我运行了你的 plunker,但我仍然无法访问原始文本。尝试将您的子组件更改为: elem.nativeElement.outerHTML += ':My new Text';你就会明白我的意思了。
  • 哦,我的错。只需将其更改为innerText。有很多方法可以做到这一点。控制台记录 elem 并使用您想要的所有属性。
  • OP可以改变innerText,他无法获取当前文本
  • 那个 += 将它添加到当前文本中,因此,你有当前文本..?
  • 太棒了!这只是回答问题,而不是建议组件或其他任何东西。当我来到这里寻找问题的答案时,我需要一个指令。太棒了,谢谢。
猜你喜欢
  • 2016-06-14
  • 1970-01-01
  • 2019-02-21
  • 1970-01-01
  • 2016-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多