在下拉选择中动态更改iFrame src

时间:2019-05-11 15:02:39

标签: javascript angular typescript

我正在尝试根据下拉列表上的选择动态更改iframe的src。我遇到错误,说使用不安全的网址,因此我如下添加了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'.

enter image description here

1 个答案:

答案 0 :(得分:1)

您似乎对应如何使用角度数据绑定缺乏理解,并且在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>

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

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);
    }
}