I am trying to create a directive that modifies the element\'s innerHTML
by adding links to those substrings which start with @
symbol.
Thi
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
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
name: 'linkify'
})
export class LinkifyPipe implements PipeTransform {
constructor(private _domSanitizer: DomSanitizer) {}
transform(value: any, args?: any): any {
return this._domSanitizer.bypassSecurityTrustHtml(this.stylize(value));
}
private stylize(text: string): string {
let stylizedText: string = '';
if (text && text.length > 0) {
for (let t of text.split(" ")) {
if (t.startsWith("@") && t.length>1)
stylizedText += `<a href="#${t.substring(1)}">${t}</a> `;
else
stylizedText += t + " ";
}
return stylizedText;
}
else return text;
}
}
Usage:
<p [innerHTML]="sample | linkify"></p>
Demo Stackblitz