Search code examples
htmlangulariframeionic4

iframe src property as a URL dynamically Angular2


I'm having a hell of a time trying to figure out how to dynamically change the URL in a iframe src. I have tried setting the variables and then using string interpolation no luck.

Any suggestions on how i can do this. Possibly some examples if you could.

sample code i was trying;

src="https://www.wheehouse.org/company/PriceMin={{ this.itemMinimum }}&PriceMax={{ this.itemMaximum }}&BedRange={{ this.itemBedRoomType }}-0&BathRange={{ this.itemBathType }}-0"

Thanks.


Solution

  • Step 1 - In HTML page - example string can be html, url, style, script etc

    [src] = "exampleString | safe: 'url'"
    

    Step 2 - Create a safe pipe

    Safe Pipe Code

    import { DomSanitizer, SafeHtml, SafeResourceUrl, SafeScript, SafeStyle, SafeUrl } from "@angular/platform-browser";
    import { Pipe, PipeTransform } from "@angular/core";
    
    @Pipe({ name: "safe" })
    export class SafePipe implements PipeTransform {
        constructor(private sanitizer: DomSanitizer) { }
    
        public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
            switch (type) {
                case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
                case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
                case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
                case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
                case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
                default: throw new Error(`Invalid safe type specified: ${type}`);
            }
        }
    }    
    

    Note: - As per safe pipe is concerned you have to implement it in order to stop DOMSanitizer to strip out content from your URL.

    Please check the below URL for how to implement safe pipe. Link