Angular4 Load external html page in a div [duplicate]
Asked Answered
B

1

12

I had an application in angular1 and I was using jquery to load an external page in my HTML element. This is the html of my container element:

<div id="externalContainer" class="text-center">
</div>

I used the following script to load the external page.

$( "#externalContainer" ).load( myExternalPageLink );

Now this doesn't seem to work in angular4, can experts guide me how can I achieve this functionality in angular4?

Baluchi answered 10/10, 2017 at 6:24 Comment(1)
I know that I am a little late to the party here, but I came across this question while trying to solve my own problem and wanted to share in case someone else had the same issue. I was trying to also allow custom components to be used in our external html for our blog. I documented it all on our blog (dynamically generate angular components from external html). Hopefully this is moderately helpful to the next person who comes across this.Whilom
C
11

You can use [innerHtml] something like

<div [innerHtml]="myTemplate">
</div>

In your component

export public class MyComponent {
    private myTemplate: any = "";
    constructor(http: Http) {
        http.get(myExternalPageLink).map((html:any) => this.myTemplate = html);
    }
}
Cofield answered 10/10, 2017 at 6:37 Comment(10)
Can i load a local file with this ?Baluchi
I tried loading a local file with this, but the myTemplate variable is empty.Baluchi
how about the inline, external style/css ? i cannot see the effects.Scaffolding
@Scaffolding You cannot see inline styles because the content is sanitised.Cognation
@RaduCojocari i used safeHtml Pipe then it worked fine! See https://mcmap.net/q/695153/-angular2-innerhtml-removes-stylingScaffolding
@Vung Yes. that will definitely work. The compromise is the fact that you are opening yourself up to security issues. If you don't care about it, then your solution makes senseCognation
What if there are jquery/javascript functions running in the external html page, will they run?Concur
@skydev no jquery/javascript will not work here for that you can dyanmically add js scriptCofield
I'm newby with angular 8. An error appears in cmd error TS2304: Cannot find name 'Http'. Do i have to import it somewhere?Dardar
@Cofield thanks, this works like I need and its implementation is very simple.Olia

© 2022 - 2024 — McMap. All rights reserved.