Reputation: 1993
I am trying to create really simple Iframe in Angular 2 project. Code
If I use raw url in iframe src, get an error unsafe value used in a resource URL context
<!-- 1) Error : unsafe value used in a resource URL context -->
<iframe (load)="yourLoadFunction()" [src]="'/'" frameborder="0" width="1000px" height="500px"></iframe>
If I use DomSanitizer.bypassSecurityTrustResourceUrl
for url sanitize, it works but Iframe load infinite time, strange hmmm. Code (check console)
<!-- 2) Infinite loop Iframe loading -->
<iframe (load)="yourLoadFunction()" [src]="sanitizer.bypassSecurityTrustResourceUrl('/')" frameborder="0" width="1000px" height="500px"></iframe>
So, I have created pipe for url as below and it's working without issue
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 sanitizer: DomSanitizer) {}
transform(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
HTML View
<!-- 3) Working with pipe -->
<iframe (load)="yourLoadFunction()" [src]="'/' | safeUrl" frameborder="0" width="1000px" height="500px"></iframe>
Now, I have questions
Why is the error unsafe value used in a resource URL context
in angular where plain html iframe works
Why DomSanitizer.bypassSecurityTrustResourceUrl
causing iframe to load infinitely but not pipe
with same function
Upvotes: 1
Views: 1443
Reputation: 7427
Because when you pass a method into template binding, the method is called each change detection cycle.
Angular can't see if the value returned from the method in the markup is the same as it was before without actually calling it.
It returns a SafeResourceUrl
, which I believe has metadata cooked into it that can change with each call.
Pipes, on the other hand, won't be called again unless the input value has changed.
This is why it's generally preferable not to bind method calls directly to an input value.
Upvotes: 4