The documentation only says:
Marker interface for a value that's safe to use as a URL linking to a document.
When should I use SafeUrl
?
You use SafeUrl
along with DomSanitizer
to tell the Dom that a URL is trusted by your app.
Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values.
For example, doing the following will result in an error:
<iframe [src]="iframeSrc"></iframe>
in your ts:
export class AppComponent {
iframeSrc: string;
constructor(){
let id = 's7L2PVdrb_8'; // Game of Thrones Intro Video
this.iframeSrc = `https://www.youtube.com/embed/${id}`;
}
}
unsafe value used in a resource URL context
To avoid this, you use SafeUrl
with DomSanitizer
to tell you app that the dynamic URL you are using is trusted:
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
export class AppComponent {
iframeSrc: SafeUrl;
constructor(private sanitizer: DomSanitizer){
let id = 's7L2PVdrb_8'; // Game of Thrones Intro Video
let url = `https://www.youtube.com/embed/${id}`;
this.iframeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
See this working demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With