如何在Angular中为iframe动态更改src?

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

我有一个mat-option标记,我希望用户从下拉列表中选择一个选项,它将自动加载与用户选择相关联的iframe src URL。

component.html

<div class="container">
<div class="row">
<div class=".col-md-10 .col-sm-10">
  <div *ngIf="selectedReport">
  <mat-card class="dashboard-card">
    <iframe width="950" height="680" ng-src="{{selectedReport.url}}" frameborder="0" allowFullScreen="true"></iframe>
  </mat-card>
  </div>
</div>

<div class=".col-md-2 .col-sm-2">
  <mat-card class="navigation-card">
    <mat-card-header>
      <mat-card-title>Report</mat-card-title>
    </mat-card-header><hr>
    <mat-card-content>
      <mat-select placeholder="Select a project">
        <mat-option *ngFor="let report of reports" [class.selected]="report === selectedReport">
          {{report.name}}
        </mat-option>
      </mat-select>
    </mat-card-content>
  </mat-card>
</div>

mock-data.ts以下不是正确的网址。提供它们以显示结构

import { Report } from './model/report';

export const REPORTS: Report[] = [
{ id: 1, name: 'Test1', url:'<iframe 
src="https://www.google.com/maps/embed?" },
{ id: 2, name: 'test2', url:"https://www.google.com/maps/embed?" }
];
angular iframe
1个回答
0
投票

我需要同样的东西,而我发现更改iframe src的唯一方法是通过nativeElement。

因此,在您的.html文件中,您的iframe需要通过#:

<iframe #myIframe ></iframe>

在您的组件中,可以像下面这样使用@ViewChild引用iframe:

@ViewChild('myIframe') myIframe: ElementRef;

如果您用完Angular 8:

@ViewChild('myIframe', {static: false}) myIframe: ElementRef;

因此,要更改src,需要在nativeElement上进行更改:

this.myIframe.nativeElement.src = 'https://en.wikipedia.org/wiki/Node.js';

对我来说很好,希望对您有所帮助!

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