简体   繁体   中英

How to save and load a page with two angular2 components from local storage?

I have been trying to save and load a page with two angular2 components from local storage with the next code but the css from components is never applied.

This is my code to save:

localStorage.setItem('body', JSON.stringify(document.getElementById("body").innerHTML));

This is my code to load:

document.getElementById("body").innerHTML=JSON.parse(localStorage.getItem("body"));

I hope to have explained my problem well

Sorry, you cannot do that. Angular likes to take over a lot of the DOM, so you cannot just replace the entire body of the DOM. However, if instead of doing the entire "body", you did a subset, then you could do this:

<div [innerHTML]="htmlVar">
</div>

Where htmlVar is a variable you loaded with something like:

this.htmlVar = JSON.parse(localStorage.getItem("htmlVar"))

Watch out, by default innerHTML will strip out lots of "unsafe" html. You can reenable most of them by calling DomSanitizer. Please note that you cannot use any Angular features in the html, like links with routerLink.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM