【问题标题】:How to render a HTML string with a directive如何使用指令呈现 HTML 字符串
【发布时间】:2019-04-15 12:01:15
【问题描述】:

我有一个用例,我需要渲染 HTML 节点并将其转换为 HTML 字符串,然后在该 HTML 字符串中的特定元素上添加 ngx-bootstrap 工具提示指令。

我可以通过使用带有管道的 InnerHTML 或创建一个单独的组件来使 HTML 呈现良好,但总是在呈现 HTML 之后,元素上的工具提示指令未注册,我不知道该去哪里从这里。虽然我会在 PIpe 上使用pure: false 来解决它,但它没有。

这是我用管道尝试过的:

带有工具提示指令的管道

import { documentToHtmlString } from '@contentful/rich-text-html-renderer';
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { BLOCKS, INLINES } from '@contentful/rich-text-types';
import { Store } from '@ngxs/store';
import { DeckState } from '../__states/deck';

@Pipe({ name: 'rich', pure: false })
export class RichContent implements PipeTransform {
  constructor(private sanitizer: DomSanitizer, private store: Store) {
  }

  transform(content) {


    let options = {
      renderNode: {
        [INLINES.EMBEDDED_ENTRY]: (node) => {
          return `<b [tooltip]="node.data.target.fields.companyName">${node.data.target.fields.companyName}</b>`
        }
      }
      }

      var html = documentToHtmlString(content, options);

      return this.sanitizer.bypassSecurityTrustHtml(html);

  }
}

HTML

<div [innerHTML]="content | rich"></div>

结果

没有工具提示指令工作或注册的纯 HTML。 例如:

<p>Here is an example from <b [tooltip]="node.data.target.fields.companyName">Mixpanel</b></p>

希望有人可以帮助我并指出正确的方向来解决这个问题。

【问题讨论】:

  • 从我的头顶..我认为出于安全原因您不能,您需要编写一个组件。检查Angular HTML binding是否有帮助

标签: angular pipe popover ngx-bootstrap contentful


【解决方案1】:

出于安全原因,您不能,您需要编写一个组件。

检查Angular 2 innerHTML (click) binding 相同的问题,但不同的情况..

Security
Sanitization example

【讨论】:

    【解决方案2】:

    我遇到过类似的情况,我试图将 ngStyle 与使用 innerHTML 渲染的内容一起使用,但我的发现(尽管我很高兴被证明是错误的)是不可能的,因为 innerHTML 内容不是由 Angular 插值。 See here.

    我的解决方案是在源代码(服务器端)而不是 Angular 中添加必要的样式。

    你能用title HTML attribute吗?看起来不如 Angular 好,但如果它只是你所追求的工具提示,它可能会成功吗?

    尽管正如rmjoia 建议的那样,您最好将所需的数据提取到新组件中,然后根据需要添加样式、工具提示等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-22
      • 2017-06-10
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2013-03-11
      • 2021-02-12
      相关资源
      最近更新 更多