Reputation: 699
I want to make site like Linkedin blog.
I could create dynamic component like this. but when I reload browser, dynamically created component is gone.
How can I cache dynamically created component to localStorage?? and How can I load dynamically component from localStorage when I reload browser ??
and one more question. Do I need ngOnDestroy() in this code?
I added localStorage part like this. but "Converting circular structure to JSON at JSON.stringify" TypeError occurred.
What is the best solution to cache array of ComponentRef objects??
⬇︎This is parent component
// I added this part
import { COMPONENTS_REFERENCES } from '../../constants';
export class ParentComponent implements OnInit {
index: number;
componentsReferences = [];
@ViewChild('viewContainerRef', { read: ViewContainerRef }) VCR: ViewContainerRef;
constructor(
private CFR: ComponentFactoryResolver) {
}
ngOnInit() {
// I added this part.
const cachedComponents = JSON.parse(localStorage.getItem(COMPONENTS_REFERENCES));
if (cachedComponents && cachedComponents.length > 0) {
this.componentsReferences = cachedComponents;
}
this.index = 1;
}
addChild() {
const componentFactory = this.CFR.resolveComponentFactory(ChildComponent);
const componentRef: ComponentRef<ChildComponent> = this.VCR.createComponent(componentFactory);
const currentComponent = componentRef.instance;
currentComponent.selfRef = currentComponent;
currentComponent.index = this.index++;
currentComponent.userId = this.user.id;
currentComponent.compInteraction = this;
this.componentsReferences.push(componentRef);
// I added this part
localStorage.setItem(COMPONENTS_REFERENCES, JSON.stringify(this.componentsReferences));
}
removeChild(index: number) {
if (this.VCR.length < 1) {
return;
}
const componentRef = this.componentsReferences.filter(x => x.instance.index === index)[0];
const component: ChildComponent = <ChildComponent>componentRef.instance;
const vcrIndex: number = this.VCR.indexOf(componentRef);
this.VCR.remove(vcrIndex);
this.componentsReferences = this.componentsReferences.filter(x => x.instance.index !== index);
// I added this part
localStorage.setItem(COMPONENTS_REFERENCES, JSON.stringify(this.componentsReferences));
}
// ... and another ChildComponent add/remove method here
}
⬇︎This is HTML of Parent component
<div>
<ng-template #viewContainerRef></ng-template>
</div>
Upvotes: 1
Views: 1016
Reputation: 30565
If you have listObject
in your parent component and cache your listObject
to localStorage
, you can get it and use it when you load your browser.
your key would be post_cache and value would be array of json object (array of posts)
PS: I dont see anything in your code which is needed to be destroyed
Upvotes: 1