简体   繁体   English

Angular 2/4 - 从DOM中删除组件,但保留在内存中

[英]Angular 2/4 - Remove component from DOM, but keep in memory

I'm trying to create multiple instances of the same component, and make them "tab-able" of a sort - basically only one of each component instance should be visible at a time. 我正在尝试创建同一组件的多个实例,并使它们“可以选择”排序 - 基本上每个组件实例中只有一个应该一次可见。 The problem is that I know about the [hidden] directive, but it doesn't work for me because I've built this huge component using a lot of ID tags in the HTML and it breaks the CSS on all but one of the components when they are all existent in the DOM at the same time (CSS rules, ya know?). 问题是我知道[hidden]指令,但它对我不起作用,因为我在HTML中使用了很多ID标签构建了这个巨大的组件,并且除了其中一个组件之外的所有组件都打破了CSS当它们同时存在于DOM中时(CSS规则,你知道吗?)。

My question is if there's a way to remove components from the DOM, but still keep them in memory (for data retension) to be re-inserted later? 我的问题是,是否有一种方法可以从DOM中删除组件,但仍然将它们保留在内存中(用于数据保留)以便以后重新插入? Thanks! 谢谢!

Update: 更新:

I was able to come up with a solution utilizing the abstract RouteReuseStrategy class. 我能够使用抽象的RouteReuseStrategy类来提出解决方案。 Info was taken from here: 信息来自这里:

https://www.softwarearchitekt.at/post/2016/12/02/sticky-routes-in-angular-2-3-with-routereusestrategy.aspx https://www.softwarearchitekt.at/post/2016/12/02/sticky-routes-in-angular-2-3-with-routereusestrategy.aspx

You can do something like the <router-outlet> does if you use a reuse strategy that actually reuses component instances. 如果您使用实际重用组件实例的重用策略,您可以执行类似<router-outlet>操作。 When you dynamically create a component 动态创建组件时

source 资源

 this.activated = this.location.createComponent(factory, this.location.length, inj, []);

source 资源

this.location.detach();

and the returned r is then passed to attach(ref, ...) 然后将返回的r传递给attach(ref, ...)

source 资源

this.location.insert(ref.hostView);

Your best bet for retaining data across components is to use a service. 保留组件间数据的最佳选择是使用服务。 I have a simple example here: http://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/ 我在这里有一个简单的例子: http//blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

I also have an example of a "tabbed" dialog using the . 我还有一个使用“标签”对话框的例子。 You can find that here: https://github.com/DeborahK/Angular-Routing in the APM-Final folder. 你可以在这里找到: https//github.com/DeborahK/Angular-Routing in APM-Final文件夹。

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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