首页 > 解决方案 > 在 Angular 中不使用 innerHTML 将锚链接添加到纯文本

问题描述

如何在不使用 Angular 中的 innerHTML 的情况下将锚链接添加到字符串?

这是我的文字I agree with the {{terms_policy}}。我想在{{terms_policy}}不使用 innerHTML 的情况下替换链接?

如果我使用innerHTML,链接可以正常工作。但没有innerHTML,它正在打印html代码。

在 Component.ts

this.policy_placeholder = `<a class='privacy_policy' href= ${link} target='_blank'> ${link_text} </a>`;

标签: javascriptangulartypescript

解决方案


用管子怎么样?这必须与 innerHtml 一起使用,这违背了 SO 的要求,但我不知道这个要求有多强。所以,为了它的价值:

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>`));
  }
}

用法

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


推荐阅读