DomSanitizer with a PipeTrasnform in ionic 3 vs ionic2

This is working for me in ionic 3.4.2. I originally got the SafePipe code from @infoproducts in this great thread. I made some tweaks to get it to work in Ionic3. Note that I am using lazy loading. Here is my pipe:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {
  constructor(protected _sanitizer: DomSanitizer) {
  }
  public transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
      case 'html':
        return this._sanitizer.bypassSecurityTrustHtml(value);
      case 'style':
        return this._sanitizer.bypassSecurityTrustStyle(value);
      case 'script':
        return this._sanitizer.bypassSecurityTrustScript(value);
      case 'url':
        return this._sanitizer.bypassSecurityTrustUrl(value);
      case 'resourceUrl':
        return this._sanitizer.bypassSecurityTrustResourceUrl(value);
      default:
        throw new Error(`Unable to bypass security for invalid type: ${type}`);
    }
  }
}

This is my pipe module. (I got errors with 3.4.2 without adding the module):

import { NgModule } from '@angular/core';
import { SafePipe } from './safe.pipe';
@NgModule({
  declarations: [
    SafePipe
    //other pipes
  ],
  imports: [
  ],
  exports: [
    SafePipe
    //other pipes
  ]
})
export class PipesModule { }

I then add the PipesModule to the imports of my page.module. Note also that you need to bind the pipe output to the innerHTML attribute of an element or you get errors, i.e.
<div [innerHTML]="unsafeString | safe:'html'"></div>

2 Likes