angular add unsafe before url in href - sanitizing unsafe URL
I am trying to open an app. Its working fine when I give a static URL. But as I create a dynamic href tag in *ngFor I can see unsafe keyword is added before the URL and it's not working.
I am running on Angular 6. And getting the Id in a service. In ngFor I am looping the result and creating a link with Id to open the app. I create a pipe but it's still not working.
Safe Pipe
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(value: any) {
return this.domSanitizer.bypassSecurityTrustUrl(value);
}
}
In the component I added the below line between ngFor tag
<a href="appName://joinTournament?id={{t.tag}} |safeurl">Join</a>
Solution 1:
You need to use your pipe within interpolation. With your way it's just a string (part of href). It means, angular does not recognize it as a pipe or part of your application. Also, you need to bind the value itself only and nothing else. In your case you can pass appName://joinTournament?id=
as a parameter to the pipe.
Here is a working solution.
Add another parameter to your pipe as follows
transform(value: any, prefix = '') {
return this.domSanitizer.bypassSecurityTrustUrl(prefix + value);
}
And change
<a href="appName://joinTournament?id={{t.tag}} |safeurl">Join</a>
to
<a [href]="t.tag | safeurl: 'appName://joinTournament?id='">Join</a>