如何使用Angular 7保存/加载动态创建的组件

时间:2019-01-05 12:53:56

标签: angular angular7 angular-dynamic-components

我想建立像Linkedin博客这样的网站。

我可以这样创建动态组件。 但是当我重新加载浏览器时,动态创建的组件消失了。

如何将动态创建的组件缓存到localStorage? 以及重新加载浏览器时如何从localStorage动态加载组件?

还有一个问题。 这段代码中需要ngOnDestroy()吗?

我这样添加了localStorage部分。但是发生了“将循环结构转换为JSON.stringify的JSON” TypeError。

缓存ComponentRef对象数组的最佳解决方案是什么?

⬇︎这是父组件

// 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
}

⬇︎这是父级组件的HTML

<div>
    <ng-template #viewContainerRef></ng-template>
</div>

1 个答案:

答案 0 :(得分:1)

如果父组件中有listObject并将listObject缓存到localStorage,则可以获取它并在加载浏览器时使用它。

您的键将是post_cache,值将是json对象的数组(帖子的数组)

PS:我看不到您的代码中需要销毁的任何东西