I am trying to dynamically change the src of the iframe depending on the selection made on the dropdown list. I ran in to error saying unsafe url usage so I added Dom Sanitizer like below
<div style="text-align:center">
<h1>
Reports
</h1>
</div>
<select (onclick) = "selectedOption($event)">
<option value="">Productivity</option>
</select>
<iframe width="1140" height="541.25" src="{{safeUrl}}" frameborder="0" allowFullScreen="true"></iframe>
The typescript is like below
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);
}
}
I added import { DomSanitizer, SafeResourceUrl, SafeUrl} from '@angular/platform-browser'; into the app.module.ts. But it errors out saying
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'.
1 Answer
You seem to lack some understanding of how the angular data-binding should be used, and you have some blatant issues in your Typescript file.
First, the constructor of your class AppComponent should be IN said class, not before:
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) {
}
...
}
Second, in your view, if you want to bind the value of src to a variable in your typescript, then use [src], like so:
<iframe width="1140" height="541.25" [src]="safeUrl" frameborder="0" allowFullScreen="true"></iframe>
The last issue is that you only declare safeUrl in the selectedOption of your component, it's not a member variable of the component itself, so the view cannot access it, you should change your component like so:
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);
}
}