Categories
Angular Answers

How to set the src attribute of an iframe without causing the unsafe value exception in Angular?

Spread the love

Sometimes, we want to set the src attribute of an iframe without causing the unsafe value exception in Angular.

In this article, we’ll look at how to set the src attribute of an iframe without causing the unsafe value exception in Angular.

How to set the src attribute of an iframe without causing the unsafe value exception in Angular?

To set the src attribute of an iframe without causing the unsafe value exception in Angular, we can create our own pipe that calls bypassSecurityTrustResourceUrl.

For instance, we write

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

@Pipe({ name: "safe" })
export class SafePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}
  transform(url) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}

to create SafePipe pipe class.

In it, we have the transform method that calls this.sanitizer.bypassSecurityTrustResourceUrl with url to make Angular ignore safety checks on the url.

The in we add SafePipe into our NgModule with

@NgModule({
  declarations: [
    //...
    SafePipe,
  ],
})
class Foo {
  //...
}

Then we can use it by writing

<iframe width="100%" height="300" [src]="url | safe"></iframe>

in our template.

We use the name value of the pipe to use it.

Conclusion

To set the src attribute of an iframe without causing the unsafe value exception in Angular, we can create our own pipe that calls bypassSecurityTrustResourceUrl.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *