首页 > 解决方案 > 在下拉选择中动态更改 iFrame src

问题描述

我正在尝试根据下拉列表中的选择动态更改 iframe 的 src。我遇到错误说不安全的 url 使用,所以我添加了 Dom Sanitizer,如下所示

<div style="text-align:center">
  <h1>
   Reports
  </h1>
  </div>
<select (onclick) = "selectedOption($event)">
  <option value="https://app.powerbi.com/reportEmbed?reportId=401c&autoAuth=true&ctid=5bd1">Productivity</option>
</select>

<iframe width="1140" height="541.25" src="{{safeUrl}}" frameborder="0" allowFullScreen="true"></iframe>

打字稿如下

import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

constructor(private sanitizer: DomSanitizer) {
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'PowerBIIntegration';
selectedValue: string = ''; 

  selectedOption( event : any){
    this.selectedValue = event.target.value;
    let safeUrl =  this.sanitizer.bypassSecurityTrustHtml(this.selectedValue);
    console.log(this.selectedValue);
  }
}

我添加import { DomSanitizer, SafeResourceUrl, SafeUrl} from '@angular/platform-browser';到 app.module.ts 中。但它错误地说

ERROR in src/app/app.component.ts(4,21): error TS1005: ',' expected. src/app/app.component.ts(4,30): error TS1005: ',' expected. src/app/app.component.ts(4,46): error TS1005: ';' expected.

i 「wdm」: Failed to compile.

ERROR in src/app/app.component.ts(4,1): error TS2304: Cannot find name 'constructor'. src/app/app.component.ts(4,13): error TS2304: Cannot find name 'private'. src/app/app.component.ts(4,21): error TS2304: Cannot find name 'sanitizer'. src/app/app.component.ts(18,25): error TS2339: Property 'sanitizer' does not exist on type 'AppComponent'.

在此处输入图像描述

标签: javascriptangulartypescript

解决方案


您似乎对应该如何使用角度数据绑定缺乏一些了解,并且您的 Typescript 文件中有一些明显的问题。

首先,你的类的构造函数AppComponent应该是 IN 所说的类,而不是之前:

import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

    ...

    constructor(private sanitizer: DomSanitizer) {
    }

    ...
}

其次,在您看来,如果您想将 的值绑定src到打字稿中的变量,请使用[src],如下所示:

<iframe width="1140" height="541.25" [src]="safeUrl" frameborder="0" allowFullScreen="true"></iframe>

最后一个问题是您只safeUrlselectedOption组件中声明,它不是组件本身的成员变量,因此视图无法访问它,您应该像这样更改组件:

export class AppComponent {
    title = 'PowerBIIntegration';
    selectedValue: string = '';
    safeUrl: string;

    constructor(private sanitizer: DomSanitizer) {
    }

    selectedOption(event : any) {
        this.selectedValue = event.target.value;
        this.safeUrl = this.sanitizer.bypassSecurityTrustHtml(this.selectedValue);
    }
}

推荐阅读