I'm trying to create a custom directive to replace the inner text of my custom directive. I can't seem to access the inner text content to apply some logic.
Here's the code:
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>';
}
}
Usage:
<text-transformer>Some text</text-transformer>
I would like to inspect the text inside the tag, in this case, "Some text". I can't seem to access it inside the directive.
Should I use component instead?
You're attempting to use a directive like most would use a component.
However, to transform text, it is a directive you want. Just change your selector.
Check out this 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)
}
}
Then use that directive from any other component like so:
<h1 text-transformer>This text will be changed</h1>
And for reference: https://angular.io/guide/attribute-directives
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With