0

I am trying to sanitize text thats coming from db i dont control and show it as html. My broken code looks as follows.

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

The error i am getting is as follows

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>

I am guessing i am missing something in my syntax but not sure what.

If i remove the safe pipe as follows it works fine and renders the text as html....(not sanitized).

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

The following pipe test also works as expected but the text wont be rendered as html.

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

The Safe pipe just sanitizes the passed string using Sanitizer from angular core as follows.

 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);
    ...}}

Thanks!

4
  • missing a " here: *ngFor="let comm of commList|async;> ? Commented Nov 14, 2017 at 6:14
  • Also missing double quotes around your HTML attribute values. Commented Nov 14, 2017 at 6:15
  • @OvidiuDolha updated.(accidentally removed the last quote when posting here). JB : not sure what you are referring. Commented Nov 14, 2017 at 6:23
  • try, <div innerHTML={{comm.text|safe : 'html'}}></div>, without square brackets Commented Nov 14, 2017 at 6:30

1 Answer 1

1

Either you can use :

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

or

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

But you have mixed both syntax [innerHTML]={{comm.text|safe : 'html'}}

You can read more about it here : https://angular.io/guide/template-syntax#interpolation----

Sign up to request clarification or add additional context in comments.

2 Comments

The first one works but not the second suggestion.Thanks! Any explanation what {{ }} does differently?
@Davvit. was missing double quotes , please try second method also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.