bunny
bunny

Reputation: 2037

how to instantiate DomSanitizationService

I need to remove unsafe from my url: unsafe:blob:http://localhost:1234/example, Below is what I did.

Script:

import {DomSanitizationService} from '@angular/platform-browser';

class example{
  public DomSanitizer: DomSanitizationService;
  public url;

  constructor() {
    this.url = 'www.example.com';
  }
}

HTML:

<a href={{DomSanitizer.bypassSecurityTrustHtml(url)}}>

However, it gives me error: TypeError: Cannot read property 'bypassSecurityTrustHtml' of undefined. I checked DomSanitizationService in @angular/platform-browser, it is an abstract class and cannot be instantiated. What is the right way to call? I saw a lot of answer like this (How to avoid adding prefix “unsafe” to link by Angular2?), the DomSanitizationService is passed from constructor but I don't understand when instantiated the class, what should be passed in. Besides, I don't want to change the contract of constructor. I would like to know what is the right way to achieve my goal. I am using angular2.

Update: Now I am able to make it work by injecting DomSanitizationService through constructor, however, in my test, I need to instantiate my component and what should be passed in for DomSanitizationService?

Upvotes: 1

Views: 3417

Answers (3)

Adrian Sawicki
Adrian Sawicki

Reputation: 708

The best way to handle it would be to create a sanitizer Pipe. Later on instead of making copy of your functionality you would be adding only something like data| sanitize:'html'.

Angular docs -> https://angular.io/api/platform-browser/DomSanitizer

Pipe creation example here.

Upvotes: 0

Vaibhav
Vaibhav

Reputation: 1499

You have to inject the DomSanitizer service in your component

import { DomSanitizer, SafeHtml } from '@angular/platform-browser';


export class Example {
    htmlData:SafeHtml
    constructor(private sanitizer: DomSanitizer) {
       this.url = 'www.example.com';
    }

    renderTab() {
       let temp=`<a href="${this.url}">`
                this.htmlData=this.sanitizer.bypassSecurityTrustHtml(temp);
            }

        }
    }

}

Use this inside html like

<span [innerHTml]="htmlData"></span>

Upvotes: 0

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41445

Need to inject the DomSanitizer through constructor

import {DomSanitizationService} from '@angular/platform-browser';

class example{ 
  public url;

   constructor(private sanitized: DomSanitizer) {

      this.url = 'www.example.com';
   }

   transform() { 
      return this.sanitized.bypassSecurityTrustHtml(this.url);
   }

}

<a href={{transform()}}>

Upvotes: 1

Related Questions