aw3123
aw3123

Reputation: 139

Adding Anchor link to plain text without using innerHTML in Angular

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

Answers (2)

&#216;ystein Amundsen
&#216;ystein Amundsen

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

ravciok
ravciok

Reputation: 71

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! :)

Upvotes: 0

Related Questions