0

I am using a pipe in an Ionic/Angular app that is transforming a text and returning a result with an html code.

This an example of how I am using my pipe:

<ion-label>
  <span>{{ text | mypipe: 'lo':'secondary' }}</span>
</ion-label>

The resulting HTML of the code within the double curls is as follows:

Loth<ion-text color='secondary'>lo</ion-text>rien

The problem is that upon execution, all I am seeing in my label is Loth<ion-text color='secondary'>lo</ion-text>rien instead of Lothlorien with the colored portion of the text (i.e: 'lo')

Any idea why I am having this behavior and how to fix it?

Thanks

Kamil Naja
  • 6,267
  • 6
  • 33
  • 47
Strider
  • 3,539
  • 5
  • 32
  • 60
  • 1
    Downvoters: Instead of a downvote without any known reason, a comment or an edit would be helpful to understand well the problem and have a question that could be more helpful to others – Strider Feb 14 '19 at 21:59

1 Answers1

2

TLDR:

When you want to render html which contains angular components you have to create/compile them dynamically in runtime.

Angular by default sanitizes anything that goes into the view. To display html in your template you have to use:

<span [innerHTML]="text | mypipe: 'lo':'secondary'"></span>

Your pipe should return SafeHtml:

@Pipe({
    name: 'mypipe'
})
export class MyPipe implements PipeTransform {

    constructor(private sanitizer: DomSanitizer) {}

    public transform(value, params): SafeHtml {
        //do whatever your pipe does and then
        return this.sanitizer.bypassSecurityTrustHtml(somethingToReturn);
    }
}

See this question.

You can also write a generic pipe, like in this article and then just use it:

<span [innerHTML]="text | mypipe: 'lo':'secondary' | safe: 'html'"></span>

But since your markup contains another angular component, it wont work. It would work with standard html markup. You want to look for a way how to not only render some html but to compile your template dynamically and create the resulting component dynamically. Something along these lines.

Ludevik
  • 6,954
  • 1
  • 41
  • 59
  • Thanks! It worked without the need of compiling the template dynamically – Strider Feb 14 '19 at 20:47
  • really? that's strange, i will try it myself too, cause we had requirements like these a year back – Ludevik Feb 14 '19 at 21:17
  • ok :) maybe it worked because the Ionic component `ion-text` implements something similar to what is pointed out by the article – Strider Feb 14 '19 at 21:30