gpt4 book ai didi

angular - 需要访问 Angular 5 指令文本

转载 作者:行者123 更新时间:2023-12-03 13:54:48 24 4
gpt4 key购买 nike

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

这是代码:

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

关于angular - 需要访问 Angular 5 指令文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49391293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com