【问题标题】:Adding Anchor link to plain text without using innerHTML in Angular在 Angular 中不使用 innerHTML 将锚链接添加到纯文本
【发布时间】:2020-11-04 09:49:54
【问题描述】:

如何在不使用 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>`;

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

使用管道怎么样?这必须与 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

【讨论】:

  • 如果此答案对您有所帮助,请随时将其标记为解决方案。
【解决方案2】:

在 Angular 中,有一个渲染器服务允许您创建一些 HTML 元素,定义一些道具,然后附加到 DOM。例如,您可以将服务与 ElementRef 一起使用,这有助于捕获一些现有元素并替换它们。 简单演示here! :)

【讨论】:

    猜你喜欢
    • 2012-11-23
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 2022-12-08
    • 1970-01-01
    • 2023-03-11
    • 2017-06-16
    相关资源
    最近更新 更多