How to allow html in return of angular2 pipe?

PipeAngular

Pipe Problem Overview


I have a pipe that returns a html string, however the string outputs escaped presumably as a default for security. I'm sure there must be an option to allow html instead but cant find it when I search docs.

How can I tell the pipe to allow actual html to render?

Pipe Solutions


Solution 1 - Pipe

Use bindings to innerHTML or outerHTML to render already escaped html. For example <span [innerHTML]="someString | toHtmlPipe"></span>. See this plunk:

@Pipe({
  name: 'wrapBold'
})
class WrapBold {
  transform(content) {
    return `<b>${content}</b>`;
  }
}

@Component({
  selector: 'my-app',
  pipes: [WrapBold],
  template: `
    <div>
      Hello <span [outerHTML]="content | wrapBold"></span>
    </div>
  `
})
export class App {
  constructor() {
    this.content = 'Angular2'
  }
}

Solution 2 - Pipe

I don't know if that is possible with a pipe. (It is, see @alexpods's answer.)

Have you considered converting your pipe into a component with an input property? I.e., whatever is feeding your pipe, make that an input property of the component. Put the HTML that the pipe generates into the component's template.

Solution 3 - Pipe

So thanks for replies.

Using the outerHTML binding suggested by @alexpods worked a treat. Didn't need to change my pipe at all.

So what I was doing before:

{{'TEXT' | hn: 'h2.whatever'}} which resulted in the correct html but escaped ie.

&lt;h2 class="whatever"&gt;TEXT&lt;/h2&gt;

Works great as: <span [outerHTML]="'TEXT' | hn:'h2.whatever'"></span>

which outputs: <h2 class="whatever">TEXT</h2>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrgbView Question on Stackoverflow
Solution 1 - PipealexpodsView Answer on Stackoverflow
Solution 2 - PipeMark RajcokView Answer on Stackoverflow
Solution 3 - PipergbView Answer on Stackoverflow