I am trying to create a directive that modifies the element's innerHTML
by adding links to those substrings which start with @
symbol.
This is what I have tried so far,
linkify.directive.ts
constructor(private elementRef: ElementRef, private renderer: Renderer2) {
let elementText = this.elementRef.nativeElement.innerHTML;
// elementText = '@user mentioned you';
console.log(`Element Text: ${elementText}`);
this.renderer.setProperty(this.elementRef.nativeElement, 'innerHTML', this.stylize(elementText));
}
and I'm using it like this
<p linkify> Hey @user check this out! </p>
While debugging I have made the following observations,
this.elementRef.nativeElement.innerHTML
always has an empty string.this.renderer.setProperty(this.elementRef.nativeElement, 'innerHTML', 'something');
is appendingsomething
to the beginning of the element's text instead of replacing.
Question 1: How to access the innerHTML
of an element?
Question 2: How to set the innerHTML of an element from a directive?
Stackblitz demonstrating the problem
I tried the documentation for Renderer2
, but it's of no help for me.
As @bryan60 suggested, The ideal way to do this is to create a pipe instead of a directive.
This is the pipe I ended up creating,
linkify.pipe.ts
Usage:
Demo Stackblitz