47

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!

All Іѕ Vаиітy
  • 24,861
  • 16
  • 87
  • 111
kalmas
  • 831
  • 1
  • 8
  • 12

5 Answers5

78

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) {}
micronyks
  • 54,797
  • 15
  • 112
  • 146
  • 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 Sep 11 '16 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 Apr 17 '18 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 Apr 18 '18 at 03:41
  • 2
    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 Apr 18 '18 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.

Sanket
  • 19,295
  • 10
  • 71
  • 82
6

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

KK Nebula
  • 121
  • 1
  • 2
  • 6
    does anybody even know how to use the sanatize method instead of bypassing securities???? – LizardKing Feb 08 '22 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 Jul 15 '22 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 May 17 '23 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

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

To include this change in ionic, you should add IonicSafeString

Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • 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](/review/late-answers/33046510) – Meet Bhalodiya Nov 02 '22 at 07:00