javascript - 在下拉选择中动态更改 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'.
解决方案
您似乎对应该如何使用角度数据绑定缺乏一些了解,并且您的 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);
}
}
推荐阅读
- elasticsearch - ElasticSearch:从存在的所有文档中删除字段(使用 Painless?)
- ios - 在后台线程崩溃中缩放图像 - UIGraphicsImageRenderer
- html - 如何在另一个项目中使用已编译的 Typescript 文件。(ts)是(.js)
- ionic4 - Ionic 4 和 ag-grid
- javascript - 在数据库中存储字典
- java - SSL 如何与带有 Spring REST API 或任何其他 REST API 的网站一起使用
- html - Boostrap 行:让行内的列居中?
- c# - DeviceInformation.FindAllAsync() 什么都不做
- sql - 用于选择其他列中不存在的值的 SQL 代码
- sql - 标记表的每个分区中前 90% 的行