2

I have a project and i have to use same component twice in one page but component didn't give permission for this so i want to use it with iframe but i couldn't find how can i set iframe src as string html. I can bind html with a div but i couldn't do this with iframe

This is my translater pipe:

@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) {}
    transform(url) {
        return this.sanitizer.bypassSecurityTrustHtml(url);
    }
}

My html page:

<div [innerHTML] = "template | safe"></div>

i can get with this method but i need a seperated page so

<iframe [src] = "template | safe"></iframe>

i need to do it with iframe.

and this is my Typescript file :

template: SafeHtml;
constructor() {
        this.template = '<button class="btn btn-lg btn-success">...</button>';
    }
2
  • I think you'd be a lot better off fixing whatever problem with the component is preventing you re-using it, instead of trying to hack around that with an iframe. Commented Apr 9, 2018 at 13:10
  • yes you are right it's better than this but i have no time and this method can improve my knowledge too because i recognize with this situation i can't bind a html to iframe and this could be neccessary like now :) Commented Apr 9, 2018 at 13:13

1 Answer 1

11

I'm not at all convinced that what you're trying to do is a good idea. It would almost certainly be easier and faster to just correct whatever in the component is preventing you re-using it...

...but that said, if you want to (effectively) set the innerHTML of an iframe you can use the HTML5 srcdoc attribute instead of src (which expects a URL):

<iframe [srcdoc] = "template | safe"></iframe>

srcdoc is not currently supported in IE or Edge. A polyfill does exist, though I've no idea how well it would interact with Angular.

(But note that the iframe still runs its own separate js context. Any communication between the iframed component and the rest of your app would need to be handled via postMessage, rather than normal angular methods -- unless the component in question is basically static once instantiated, this is what probably makes the strategy a non-starter.)

Incidentally, you have badly misnamed that pipe transform. It is the opposite of "safe", given that it exists solely to bypass the input sanitizer and leaves you open to XSS attacks.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.