Change Iframe Src Dynamically in Angular.

How to Change Iframe Src Dynamically in Angular?

  • How-To
  • 2 mins read

In Angular, you can dynamically change the src attribute of an iframe by leveraging property binding. Here's a step-by-step guide to achieve this:

Step 1: Define a Property in Your Component
In your component class, create a property to store the URL for the iframe.

import { Component } from '@angular/core';

@Component({
  selector: 'app-dynamic-iframe',
  templateUrl: './dynamic-iframe.component.html',
  styleUrls: ['./dynamic-iframe.component.css']
})
export class DynamicIframeComponent {
  iframeSrc: string = 'https://initialurl.com';
  
  changeIframeSrc(newUrl: string) {
    this.iframeSrc = newUrl;
  }
}

Step 2: Bind the Property to src in the Template
Use Angular's property binding to connect the iframeSrc property to the iframe's src attribute in the template.

<!-- dynamic-iframe.component.html -->
<iframe [src]="iframeSrc | safeUrl" width="500" height="300"></iframe>

Step 3: Create a Safe URL Pipe
(Optional) If you need to sanitize the URL, create a custom pipe that uses DomSanitizer to allow the URL to be safely used in the src attribute.

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

@Pipe({
  name: 'safeUrl'
})
export class SafeUrlPipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}

  transform(url: string): SafeResourceUrl {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}

Declare the pipe in your module:

@NgModule({
  declarations: [
    // ... other declarations ...
    SafeUrlPipe
  ],
  // ... other module properties ...
})
export class AppModule { }

Step 4: Update the iframeSrc Property
To change the src of the iframe, update the iframeSrc property. This can be done based on user interactions or other application logic.

// Function to change the iframe source
updateIframeSource() {
  this.changeIframeSrc('https://newurl.com');
}

Step 5: Invoke the Change Function
You can bind the updateIframeSource function to an event like a button click to trigger the source change for the iframe.

<button (click)="updateIframeSource()">Change Iframe Source</button>

By following these steps, you can dynamically change the src attribute of an iframe in your Angular application. Remember to handle URL sanitization if necessary to avoid security risks.