Correct way Provide DomSanitizer to Component with Angular 2 RC6
Asked Answered
C

5

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!

Constitute answered 11/9, 2016 at 16:5 Comment(0)
B
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) {}
Blanks answered 11/9, 2016 at 16:10 Comment(4)
This was my problem. I was attempting to use DomSanitizer as a provider. With no provider at all it works like a charm. Thanks!Constitute
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?Damnable
@Damnable it has nothing to do with Module/Submodule. Just import DOMSanitizer as shown in the component itself and use it.Blanks
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?Damnable
L
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.

Lactary answered 11/9, 2016 at 16:10 Comment(1)
Do not simply circumvent DOM sanitizing! You'll make your page vulnerable to XSS attacks!Chauffeur
L
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

Lohr answered 15/7, 2021 at 12:57 Comment(3)
does anybody even know how to use the sanatize method instead of bypassing securities????Bide
@nicholaslabrecque This is the danger of StackOverflow. Tons of posts tell people to circumvent warnings instead of properly handling them.Chauffeur
@Bide It's leaking into chatgpt, if you ask it how to use the sanitizer in Angular it suggests "bypassSecurityTrustHtml" LOLLn
A
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

Avoirdupois answered 11/9, 2016 at 16:10 Comment(2)
it should be private sanitizer:DomSanitizer onlyBlanks
Actually both should work the same github.com/angular/angular/blob/…Werth
B
0

To include this change in ionic, you should add IonicSafeString

Blow answered 27/10, 2022 at 18:11 Comment(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 ReviewZippora

© 2022 - 2024 — McMap. All rights reserved.