Angular5。如何动态地添加链接到包含特定标签的字符串。喜欢 '@'

Jon*_*aem 3 html string anchor typescript angular

我有一个看起来像这样的模板视图

<div class="post-content">
      <p>{{ post.content }}</p>
</div>
Run Code Online (Sandbox Code Playgroud)

其中post.content是字符串的一种类型。

该字符串可以包含一个或多个引用不同用户的@标记,也可以不包含。例如:“ @用户名”。我想通过链接使该标签可点击。将其作为定位标记插入的种类:

<a>@username</a>
Run Code Online (Sandbox Code Playgroud)

到目前为止,我尝试过手动对其进行字符串操作,然后将锚标签插入字符串中。但是,这只是在视图中显示为纯文本。

我该如何在Angular 5中做到这一点?

cyb*_*e92 7

您必须使用该innerHTML属性将提供的字符串呈现为HTML,因此,

<p> {{post.content}} </p>
Run Code Online (Sandbox Code Playgroud)

你应该用

<p [innerHTML]="post.content"></p>
Run Code Online (Sandbox Code Playgroud)

演示版

但是,这种方法并不安全,如果处理不当,很容易发生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;
  }

}
Run Code Online (Sandbox Code Playgroud)

您可以stylize根据逻辑修改方法。

用法:

<p [innerHTML]="sample | linkify"></p>
Run Code Online (Sandbox Code Playgroud)

演示Stackblitz