【问题标题】:Recreating previously created dynamic components using Angular 7使用 Angular 7 重新创建以前创建的动态组件
【发布时间】:2019-11-13 00:53:00
【问题描述】:

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

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);

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

一切正常,我在每个页面上都创建了一个组件列表。但是,如果用户单击“上一页”按钮,我会陷入困境。我不确定如何使用存储在 this.components 对象中的组件重新填充容器?

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

这是正确的方法,还是我应该以不同的方式研究它? 谢谢。

【问题讨论】:

    标签: javascript html angular typescript angular-components


    【解决方案1】:

    这是一种使用动态组件的有趣方法。您是否尝试过 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());
    

    【讨论】:

    • 谢谢。这看起来是正确的路径。我试过了,当我再次插入它时,它只返回视图中的最后一个组件。让我检查一下,我会尽快更新评论。谢谢
    • 编辑:刚刚发现 detach 需要一个索引,否则它只会在容器中插入最后一个视图 :)
    【解决方案2】:

    感谢下面 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])
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 2019-05-31
      • 2017-02-24
      • 1970-01-01
      • 2017-09-10
      • 2011-12-22
      相关资源
      最近更新 更多