1

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>`;
aw3123
  • 139
  • 5
  • 18

2 Answers2

2

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

Øystein Amundsen
  • 3,993
  • 8
  • 44
  • 63
0

In angular, there is a renderer service that allows you to create some HTML elements, define some props, and append then to the DOM. You can use the service with ElementRef which helps catch some existing elements and replace them, for example. Simple demo here! :)

react_or_angluar
  • 1,568
  • 2
  • 13
  • 20
ravciok
  • 71
  • 3