【问题标题】:Angular2: Escape string inside an html attributreAngular 2:在 html 属性中转义字符串
【发布时间】:2017-02-06 22:50:15
【问题描述】:

所以我正在尝试使用 ng-bootstrap 组件将引导程序集成到我的 Angular 2 应用程序中。

按照教程,我创建了一个类似手风琴的结构来显示我从服务器获取的文章。

模板是这样的

<ngb-accordion *ngFor="let article of articles">
  <ngb-panel title="{{ article.title }}">
    <template ngbPanelContent>{{ article.summary }}</template>
  </ngb-panel>
</ngb-accordion>

问题在于article.title和article.summary可能包含特殊的html字符,比如

&quot;

那么,有没有办法把它变成单引号(')? 到目前为止,我发现的所有解决方案都是在元素中注入 html,这不是我的情况。

任何信息都会有很大帮助。 谢谢!

【问题讨论】:

    标签: angular html-escape-characters ng-bootstrap


    【解决方案1】:

    使用正则表达式将那些特殊字符替换为空字符串

    <ngb-accordion *ngFor="let article of articles">
      // Add this line, escape it so it won't terminate prematurely
      // Note: no curly braces
      <ngb-panel title="article.title.replace(/\"/g, '')">
        <template ngbPanelContent>{{ article.summary }}</template>
      </ngb-panel>
    </ngb-accordion>
    

    【讨论】:

    • 对不起,我的问题搞砸了。我正在寻找输出&QUOT; (减去第一个空格):) 现在编辑
    • 正确。但请注意,我不知道会出现哪些符号(文章来自 rss 提要)。我有点希望有一种标准的方法来做到这一点,就像对带有innerHTML指令的元素所做的那样(在此处描述lishman.io/angular-2-interpolation
    • 我很困惑你的问题。所以您的article.title 包含像&amp;quot; 这样的html 实体,并且您想将这些html 实体输出为常规字符,所以将&amp;quot; 转换为"?或从"&amp;quot;
    • 那么你应该使用单引号' 将你的表达式括起来。 &lt;ngb-panel title='{{article.title}}'&gt; 这样,您就不必担心双引号会过早终止您的表达式
    • 我会试试这个!
    猜你喜欢
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    • 2014-10-13
    • 1970-01-01
    • 2017-06-13
    • 2017-09-20
    相关资源
    最近更新 更多