I was getting this error when using an iframe so there I fixed using [src]
as below:
Note: Use pipes for better performance
Import this:
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
constructor(private sanitizer: DomSanitizer, ....other DI){}
In ts file
getSafeUrl() {
return this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
}
In html file
<iframe [src]="getSafeUrl()" frameborder="0" *ngIf="url"></iframe>
This method is quite cycle consuming as it'll call the function multiple time so it's better to sanitize URL inside lifeCycleHooks like ngOnInit()
.
You can use pipes as well for better performance:
Using Pipe
HTML:
<iframe [src]="url | byPassSecurity"></iframe>
Sanitize.pipe.ts:
import { Pipe, PipeTransform, SecurityContext } from "@angular/core";
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Pipe({
name: 'byPassSecurity'
})
export class ByPassSecurityPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform (value: string): SafeHtml {
return this.sanitizer.bypassSecurityTrustHtml(value);
}
}