使用管道时AngularJS模板解析错误

时间:2017-11-14 06:11:22

标签: angular typescript angular-pipe

我正在尝试清理来自db的文本,我不控制并将其显示为html。我破碎的代码如下所示。

 <li *ngFor="let comm of commList|async;">
    <div class="notifBody">
      <span>
        <div [innerHTML]={{comm.text|safe : 'html'}}> </div>
      </span>
    </div>
 </li>

我得到的错误如下

compiler.es5.js:1694 Uncaught Error: Template parse errors:
Unexpected closing tag "div". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags ("
      <hr>
      <span>
        <div [innerHTML]={{comm.text|safe : 'html'}}>[ERROR ->]</div>
      </span>
    </div>

我猜我的语法中缺少一些东西,但不确定是什么。

如果我按如下方式移除安全管道,它可以正常工作并将文本呈现为html ....(未经过消毒)。

    <div class="notifBody">
      <span>
        <div [innerHTML]=comm.text></div>
      </span>
    </div>

以下管道测试也按预期工作,但文本不会呈现为html。

<div class="notifBody">
  <span>
    {{comm.text|safe : 'html'}}
  </span>
</div>

Safe管道只是使用角度核心的Sanitizer清理传递的字符串,如下所示。

 import { Pipe, Sanitizer, SecurityContext } from '@angular/core';
 ...
 public transform(value: string, type: string): string {
    switch (type) {
        case 'html':
            return this.sanitizer.sanitize(SecurityContext.HTML, value);
    ...}}

谢谢!

1 个答案:

答案 0 :(得分:1)

你可以使用:

[innerHTML]="comm.text|safe : 'html'"

innerHTML="{{comm.text|safe : 'html'}}"

但你混合了两种语法[innerHTML]={{comm.text|safe : 'html'}}

您可以在此处详细了解:https://angular.io/guide/template-syntax#interpolation----

相关问题