Ionic - InnerHTML alternative

Viewed 7168

I am have a variable which fetches a string from my database and displays it on one of my panels. The text which is fetched contains typical HTML tags such as <b><u><p> etc.

<div [innerHTML]="myVariableWithTags"></div>

This would work when tested with ionic lab but will not run on emulators or real devices.

So my question is what is an alternative of innerHTML for Ionic?

For example my variable myVariableWithTags is the following:

<b>This has to be bold</b> <i>and this italic</i>

I want to do the following:

<div> {{myVariableWithTags}} </div>

and would like to see the panel look like this: This has to be bold and this italic

instead of <b>This has to be bold</b> <i>and this italic</i>

Is this possible?

3 Answers

step 1: create a pipe

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer} from '@angular/platform-browser';

@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}
  transform(html) {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

Step 2 : Declare and exports it on app.module.ts

import { SafePipe } from '........';
@NgModule({
    declarations: [
    SafePipe
    ],
    imports: [

    ],
    exports: [
        SafePipe
    ],
    providers: [
    ]
})

step 3: use safe pipe on html file

<div [innerHTML]="myVariableWithTags | safe"></div>

InnerHTML Supported in IONIC-4 version

<ion-content padding>
    <div [innerHTML]="data"></div>
</ion-content>  

**Don't use inside of "<p>" tag.

Wrap myVariableWithTags in a <span>. This worked for me.

Related