Angular 中嵌入标签的 src 属性绑定时出现问题

问题描述 投票:0回答:1

我正在尝试使用属性绑定动态绑定 Angular 中嵌入标签的 src 属性,但它没有按预期工作。

这是我尝试过的: 在我的 TypeScript 文件中,我声明了一个属性来保存源 URL:

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

在我的模板文件(component.html)中,

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

但是,PDF 文件未加载到嵌入标签中。我已经仔细检查了 embedSource 的值,它包含 PDF 文件的正确 URL 路径。 谁能帮我找出可能导致此问题的原因吗?

angular pdf embed angular-binding
1个回答
0
投票

PDF 不会在 stackblitz 中渲染,但下面的示例代码可能会帮助您实现所需的效果。我们需要使用

DomSanitizer
方法
bypassSecurityTrustResourceUrl
这样 Angular 才会信任 URL 并加载资源!

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 演示

© www.soinside.com 2019 - 2024. All rights reserved.