Search code examples
angularangular-templateangular-pipe

Rendering HTML inside double curly braces


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


Solution

  • 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.