4

I have a function witch gets html content from file as a string. After that I made it as a html object. I can clearly see it in my console that it works. How to pass it from a service to a div element ?

nav.service.ts :

html: string;
      public  getZipFileContent(urlPath:string, pathInZip:string, ) {
        getFileContentFromRemoteZip(urlPath, pathInZip, (content) => {
          console.log(content);
          let html = content; 
          let htmlObject = document.createElement('div');
          htmlObject.innerHTML = html;
          console.log(htmlObject);
          this.html = html; // it's a string
          this.html = htmlObject // error : can't asign string as HTMLdivElement
        });
      }
    }

What I get now by adding {{navSrv.html}} in my component :

enter image description here

What I want to get :

Hello

Console.log from : console.log(htmlObject);

enter image description here

How to get htmlObject and use it as a variable ?

1

2 Answers 2

13

you can do it like follow if you want it in div only then

<div [innerHtml]="navSrv.html"></div>

Apart from this you can also do it like below :

<div #divID ></div>

And then bind it like this way

@ViewChild('divID') divID: ElementRef;

loadHtml(){
    this.divID.nativeElement.innerHTML = this.html;
}

The second part is useful when the html string is very much large.

EDIT

As your requirement if you have <script> tag then you can do if as follows

const element = document.createRange().createContextualFragment(this.html);
this.divID.appendChild(fragment);
Sign up to request clarification or add additional context in comments.

9 Comments

What if HTML string got <script> in it, and I only see js as a string with [innerHTML].
what are you getting right now ? I think It will work but I doubt that the code under the tag won't work
Now i am using <div [innerHtml]="navSrv.html"></div> . My navSrv.html is .html document with lot's of javascript code. I get javascript as a string.
Check my updated answer. May be you will get your answer.
I get error "Cannot read property 'nativeElement' of undefined" . I wrote in a class : @ViewChild('html') html: ElementRef; loadHtml(){ this.html.nativeElement.innerHTML = this.navSrv.html; }
|
1

For this you can use innerHTML it will make sure your html will be shown correctly:

<div [innerHTML]="navSrv.html"></div>

2 Comments

Omg.. 2 hours for this?? Hate when this happens. Thank you
what if in that html is <script> tag where js is written ? I get js as a string.

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.