使用 Angular 7 重新创建以前创建的动态组件

Recreating previously created dynamic components using Angular 7

我正在使用以下代码动态创建组件:

components = {}
....
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentClass);
const component = this.container.createComponent(componentFactory);

// Push the component so that we can keep track of which components are created
this.components[pageNumber].push(component);

现在,我正在尝试模仿多页面表单行为,因此当用户单击 "Next Page" 时,我使用 this.container.clear() 清除容器并使用新页面的组件重新填充它。

一切正常,我在每个页面上都创建了一个组件列表。但是,如果用户单击 "Previous Page" 按钮,我不知道该怎么办。我不确定如何使用存储在 this.components 对象中的组件重新填充容器?

我无法再次推送新组件,因为用户可以修改它们的值,重新创建它会重置所有值。

这是正确的方法吗,还是我应该换一种方式来研究它? 谢谢

这是一种有趣的动态组件方法。您是否尝试过 ViewContainerRef 的 detach() 和 insert() 方法,如下所示 -

const viewRef = this.container.detach();
this.viewRefs[pageNumber].push(viewRef);

// after coming back to the page
this.container.insert(this.viewRefs[pageNumber].pop());

感谢下面 Uday Vunnam 的代码,终于让它工作了。这是最终的工作代码。不过,我会接受 Uday 的回答,因为它让我走上了正确的道路,让我免于编写很多不必要的代码!

最初,

this.viewRefs = {}

从容器中分离视图:

this.viewRefs[this.currPage] = [];
//The line below was added as the container pops values mid-loop, disturbing the length
let containerLength = this.container.length;
for(let i=0; i<containerLength; i++){
  //Detach the 0 index always, as the container values are being popped put internally.
  this.viewRefs[this.currPage].push(this.container.detach(0));
}

用于在新页面中附加视图:

for(let i=0; i<this.viewRefs[this.currPage].length; i++){
  this.container.insert(this.viewRefs[this.currPage][i])
}