angularpdfembedangular-binding

Trouble binding src attribute of embed tag in Angular


I'm trying to dynamically bind the src attribute of an embed tag in Angular using property binding, but it's not working as expected.

Here's what I've tried: In my TypeScript file, I have declared a property to hold the source URL:

export class MyComponent {
 embedSource: string = 'pathtofile.pdf';
}

In my template file (component.html),

<embed [src]="embedSource" type="application/pdf" width="100%" height="600px">

However, the PDF file is not loading in the embed tag. I've double-checked the value of embedSource, and it contains the correct URL path to the PDF file. Could anyone please help me figure out what might be causing this issue?


Solution

  • The PDF does not get rendered in the Stackblitz, but the below sample code might help. We need to use the DomSanitizer method bypassSecurityTrustResourceUrl. So that Angular will trust the URL and load the resource.

    import { Component } from '@angular/core';
    import {
      DomSanitizer,
      SafeUrl,
      bootstrapApplication,
    } from '@angular/platform-browser';
    import 'zone.js';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      template: `
        <embed [src]="embedSource" type="application/pdf" width="100%" height="600px">
      `,
    })
    export class App {
      embedSource: SafeUrl = '';
    
      constructor(private sanitizer: DomSanitizer) {
        this.embedSource =
          this.sanitizer.bypassSecurityTrustResourceUrl('assets/dummy.pdf');
      }
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo