How can I avoid adding prefix “unsafe” to a link by Angular 2?

Angular

Angular Problem Overview


Using Angular 2, is there a setting to avoid adding prefix “unsafe:” to links. I need to set links for a protocol which is not whitelisted by default in Angular 2, but it is needed for our internal application, so the result is an invalid link:

    <a href="unsafe:Notes://MYSERVER/C1256D3B004057E8" ..

In older Angular there was compileProvider.aHrefSanitizationWhitelist, but I cannot find something similar in Angular 2.

Angular Solutions


Solution 1 - Angular

Use the DomSanitizer:

import {DomSanitizer} from '@angular/platform-browser';
...
constructor(private sanitizer:DomSanitizer){}
...
let sanitizedUrl = this.sanitizer.bypassSecurityTrustUrl('Notes://MYSERVER/C1256D3B004057E8');

or create a method to return the sanitized url:

sanitize(url:string){
    return this.sanitizer.bypassSecurityTrustUrl(url);
}

and then in your template:

<a [href]="sanitize('Notes://MYSERVER/C1256D3B004057E8')" ..

Demo Plunk

Solution 2 - Angular

Another way is you can create a pipe service to change an unsafe URL to a safe URL, so there isn't any need to rewrite the code in all components. Create a pipe service called safe-url.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({
  name: 'safeUrl'
})
export class SafeUrlPipe implements PipeTransform {
  constructor(private domSanitizer: DomSanitizer) {}
  transform(url) {
    return this.domSanitizer.bypassSecurityTrustResourceUrl(url);
  }
}

Then use it in your view.

Example:<a [href]="'Notes://MYSERVER/C1256D3B004057E8' | safeUrl"></a>

NOTE: Don't forget to inject this pipe service in your app.module.ts file:

import { SafeUrlPipe } from './shared/safe-url.pipe'; // Make sure your safe-url.pipe.ts file path is matching.

@NgModule({ declarations: [SafeUrlPipe],...});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVeljacView Question on Stackoverflow
Solution 1 - AngularAbdulrahman AlsoghayerView Answer on Stackoverflow
Solution 2 - AngularAmruthView Answer on Stackoverflow