我有一个看起来像这样的模板 View
<div class="post-content">
<p>{{ post.content }}</p>
</div>
其中 post.content 是一种字符串。
该字符串可能包含也可能不包含一个或多个引用不同用户的@ 标记。示例:“@用户名”。我想让这个标签可以通过链接点击。将其作为 anchor 标记插入:
<a>@username</a>
到目前为止,我已经尝试过手动对它进行字符串操作,并在字符串中插入 anchor 标记。然而,这只是在 View 中显示为纯文本。
我如何在 Angular 5 中解决这个问题?
最佳答案
您必须使用 innerHTML
属性将提供的字符串呈现为 HTML,
所以不是
<p> {{post.content}} </p>
你应该使用
<p [innerHTML]="post.content"></p>
但是,这个方法是not safe处理不当容易发生XSS,
推荐的方法:使用 DOM Sanitization 创建管道
linkify.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
name: 'linkify'
})
export class LinkifyPipe implements PipeTransform {
constructor(private _domSanitizer: DomSanitizer) {}
transform(value: any, args?: any): any {
return this._domSanitizer.bypassSecurityTrustHtml(this.stylize(value));
}
// Modify this method according to your custom logic
private stylize(text: string): string {
let stylizedText: string = '';
if (text && text.length > 0) {
for (let t of text.split(" ")) {
if (t.startsWith("@") && t.length>1)
stylizedText += `<a href="#${t.substring(1)}">${t}</a> `;
else
stylizedText += t + " ";
}
return stylizedText;
}
else return text;
}
}
你可以根据自己的逻辑修改stylize
方法。
用法:
<p [innerHTML]="sample | linkify"></p>
关于html - Angular 5. 如何动态添加指向包含特定标签的字符串的链接。像 '@',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48449708/