How about using a pipe? This must be used with innerHtml though, which goes against the requirement of the SO, but I don't know how strong that requirement is. So, for what it's worth:
import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
@Pipe({ name: 'link', })
export class ToLinkPipe implements PipeTransform {
constructor(private sanitize: DomSanitizer) {}
transform(value: any, type?: string): any {
return this.textToLinks(value);
}
textToLinks(value: string): SafeHtml {
const linkRegex = /https?:\/\/\S+/gm;
return this.sanitize
.bypassSecurityTrustHtml(value.replace(linkRegex, (m, $1) => `<a href="${m}">${m}</a>`));
}
}
Usage
export class AppComponent {
termsPolicy = 'http://terms.policy.com';
get text() { return `I agree with the ${this.termsPolicy}`; }
}
<span [innerHtml]="text | link"></span>
https://stackblitz.com/edit/to-link-pipe