0

I am new to Angular, and I am trying to convert my unsafe URL to a safe URL. I searched here to rectify this problem using pipe, but I don't see it converted to safe, may be something I am missing.

My pipe.ts file looks as below:

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(value: any, args?: any): any {
    return this.domSanitizer.bypassSecurityTrustHtml(value);
  }
}

Part of my template looks as below:

<tr *ngFor="let myData of data"> // Data is coming the from component.ts file

    <td> <a href='my://problem/{{myData.Id}} | safeUrl'>myLink</a></td>
</tr>

In the UI, when I inspect, it appears to be like unsafe: my://problem/55316480 | safeUrl. But I expect it to appear as my://problem/55316480

How can I fix it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
learner
  • 475
  • 3
  • 9
  • 23

2 Answers2

1
<tr *ngFor="let myData of data"> // data is coming from component.ts file

<td> <a href='my://problem/{{myData.Id}} | safeUrl'>myLink</a></td>

The issue is that 1) you are passing a string to href instead of an expression. 2) bypass the wrong property

Try

<td> <a [href]="('my://problem/' + myData.Id) | safeUrl">myLink</a></td>
    return this.domSanitizer.bypassSecurityTrustUrl(value);

Demo: https://stackblitz.com/edit/angular-pi4mn8

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
juana pu
  • 161
  • 1
  • 7
  • I tried, now get this error: Uncaught Error: Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected at column 16 in ['my://problem/{{myData.Id}}' | safeUrl] in.... – learner Sep 20 '19 at 01:38
  • Its not syntactically incorrect. ```unexpected token myData``` – learner Sep 20 '19 at 02:20
  • attached a demo and edited answer. bypass and template reference syntax issue. – juana pu Sep 20 '19 at 02:34
  • Awesome ! . Worked. – learner Sep 20 '19 at 03:01
  • What is the intent of "p" in ```p in the Markdown source (the first line)? In that position there would normally be something like `lang-none`, `lang-html`, `lang-javascript`, etc. You can [edit your answer](https://stackoverflow.com/posts/58020588/edit) (e.g., to remove the "p" if it was not intended to be there). – Peter Mortensen Jan 13 '21 at 20:22
0
<td> <a [href]="('my://problem/' + myData.Id) | safeUrl">myLink</a></td>
Hsuan Lee
  • 2,300
  • 1
  • 10
  • 18
  • doesn't work. See below error: ERROR Error: Required a safe URL, got a HTML (see http://g.co/ng/security#xss) – learner Sep 20 '19 at 02:04
  • Realized that apart from above, had to return ```return this.domSanitizer.bypassSecurityTrustUrl(value);``` in `pipe.ts` – learner Sep 20 '19 at 03:06