javascript - 在 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>`;
解决方案
用管子怎么样?这必须与 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>
推荐阅读
- python - 正则表达式输入 1 ,2 ,3 到列表中
- composer-php - 通过 Composer 处理分叉的 GitHub 存储库
- python-2.7 - 具有可变列名的 Pandas 数据框查询
- c# - winform鼠标事件到wpf用户控件
- c# - GET 和 POST 在 webapi 上使用 POST 带参数但 GET 不带参数
- ios - FFmpeg 构建错误“未找到 openssl”(适用于 Mac 上的 iOS)
- c++ - 在 dlopen 之后使用 fork
- actions-on-google - 如何处理在对话流中分为 2 个实体的实体?
- http - IIS 服务器状态 500 错误 0x8007000d - web.config 中的“格式错误的 xml 元素”是什么?
- rust - 如何将特征对象转换为“子特征”对象?