49

I'm attempting to use DomSanitizer to sanitize a dynamic URL within a Component using I can't seem to figure out what the correct way to specify a Provider for this service is.

I'm using Angular 2.0.0-rc.6

Here's my current component:

@Component({
    templateUrl: './app.component.html',
    styleUrls: [ './app.component.css' ],
    providers: [ DomSanitizer ],
})
export class AppComponent implements OnInit
{
    public url: SafeResourceUrl;

    constructor(private sanitizer: DomSanitizer) {}

    ngOnInit() {
        let id = 'an-id-goes-here';
        let url = `https://www.youtube.com/embed/${id}`;

         this.videoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }

    ngOnDestroy() {}
}

This results in the error this.sanitizer.bypassSecurityTrustResourceUrl is not a function at runtime.

Could someone show me an example of how to properly provide a Provider for DomSanitizer? Thanks!

0

5 Answers 5

82

You don't need to declare providers: [ DomSanitizer ] anymore.
Just need to import DomSanitizer as shown below,

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

in component inject it through a constructor as below,

constructor(private sanitizer: DomSanitizer) {}
4
  • 1
    This was my problem. I was attempting to use DomSanitizer as a provider. With no provider at all it works like a charm. Thanks!
    – kalmas
    Commented Sep 11, 2016 at 16:22
  • What if the component that I am trying to use is inside a module that is a sub module. Inside the sub module I am importing CommonModule instead of BrowserModule. How should I provide DomSanitizer to the component inside submodule in that case?
    – TerNovi
    Commented Apr 17, 2018 at 15:21
  • @TerNovi it has nothing to do with Module/Submodule. Just import DOMSanitizer as shown in the component itself and use it.
    – micronyks
    Commented Apr 18, 2018 at 3:41
  • 3
    Ok I did try it. I am not sure if it is because the Submodule is actually part of a library that I have built using ng-packagr. I am consuming this library inside my Application project. However, I still get an error saying no provider has been provided for DomSanitizer. I ended up just doing a native JavaScript implementation to substitute the operation that I was trying to use from DomSanitizer. I am still learning about creating angular packaged libraries so I am not sure if this is affecting the import here. Would you have experience with developing libraries?
    – TerNovi
    Commented Apr 18, 2018 at 13:10
14

Import these-

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

define variable-

trustedDashboardUrl : SafeUrl;

Use it in constructor like this-

constructor(
    private sanitizer: DomSanitizer) {}

Specifiy URL like this-

this.trustedDashboardUrl =
                        this.sanitizer.bypassSecurityTrustResourceUrl
                            ("URL");

See if this helps.

1
  • 2
    Do not simply circumvent DOM sanitizing! You'll make your page vulnerable to XSS attacks!
    – mneumann
    Commented Jul 15, 2022 at 12:16
7

It is more easy if you can added custom pipe for SanitizedHtmlPipe. because we can use globally in angular project:

  • sanitized-html.pipe.ts

    import { Pipe, PipeTransform } from '@angular/core';
    import { DomSanitizer } from '@angular/platform-browser'
    @Pipe({
      name: 'sanitizedHtml'
    })
    export class SanitizedHtmlPipe implements PipeTransform {
      constructor(private sanitized: DomSanitizer) {}
      transform(value: any): any {
        return this.sanitized.bypassSecurityTrustHtml(value);
      }
    }

  • hero.component.html

    <div [innerHTML]="htmlString | sanitizedHtml"></div>

  • hero.component.ts

    import { Component, OnInit } from '@angular/core';
    @Component({
      selector: 'app-hero',
      templateUrl: './hero.component.html',
      styleUrls: ['./hero.component.css']
    })
    export class HeroComponent implements OnInit {
      htmlString: any;
      constructor() { }
      ngOnInit(): void {
        this.htmlString = `
        <div class="container">
          <header class="blog-header py-3">
            <div class="row flex-nowrap justify-content-between align-items-center">
              <div class="col-4 pt-1">
                <a class="text-muted" href="#">Subscribe</a>
              </div>
              <div class="col-4 text-center">
                <a class="blog-header-logo text-dark" href="#">Large</a>
              </div>
              <div class="col-4 d-flex justify-content-end align-items-center">
                <a class="text-muted" href="#">
                  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mx-3"><circle cx="10.5" cy="10.5" r="7.5"></circle><line x1="21" y1="21" x2="15.8" y2="15.8"></line></svg>
                </a>
                <a class="btn btn-sm btn-outline-secondary" href="#">Sign up</a>
              </div>
            </div>
          </header>
        </div>`;
      }
    }

For more information you can visit this link

3
  • 7
    does anybody even know how to use the sanatize method instead of bypassing securities????
    – LizardKing
    Commented Feb 8, 2022 at 15:38
  • 1
    @nicholaslabrecque This is the danger of StackOverflow. Tons of posts tell people to circumvent warnings instead of properly handling them.
    – mneumann
    Commented Jul 15, 2022 at 12:15
  • @LizardKing It's leaking into chatgpt, if you ask it how to use the sanitizer in Angular it suggests "bypassSecurityTrustHtml" LOL
    – Collin
    Commented May 17, 2023 at 20:18
4

Both should work

constructor(private sanitizer: DomSanitizer) {}
constructor(private sanitizer: Sanitizer) {}

Injecting DomSanitizer is better because only this type provides the necessary methods without casting.

Ensure you have imported the BrowserModule

@NgModule({
  imports: [BrowserModule],
})

See also In RC.1 some styles can't be added using binding syntax

2
0

To include this change in ionic, you should add IonicSafeString

1
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review Commented Nov 2, 2022 at 7:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.