Reputation: 139
How do I add anchor link to a string without using innerHTML in Angular ?
This is my text I agree with the {{terms_policy}}
. I wanted to replace {{terms_policy}}
to link without using innerHTML ?
If I use, innerHTML, links are working. but without innerHTML, it is printing the html code.
in Component.ts
this.policy_placeholder = `<a class='privacy_policy' href= ${link} target='_blank'> ${link_text} </a>`;
Upvotes: 1
Views: 1240
Reputation: 4203
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
Upvotes: 3