【问题标题】:Adding / Removing components on the fly即时添加/删除组件
【发布时间】:2016-03-09 16:48:45
【问题描述】:

我需要能够动态添加和删除 Angular 组件。为此,我使用了 loadIntoLocation 和 dispose 方法,例如:

添加组件(从布局管理器):

this.m_loader.loadIntoLocation(MyComponent, this.m_element, 'content').then(_componentRef => {

    // Create the window and set its title:
    var component: MyComponent = (_componentRef.instance);
    component.ref = _componentRef;

    // init the component content
});

移除一个组件(从组件中):

this.ref.dispose();

它几乎可以工作了: - 如果我添加一个组件并关闭它,它就可以工作 - 如果我添加几个组件,它们就可以工作 - 但是如果我添加组件 A,然后删除它,然后添加组件 B,看起来 Angular 给了我对 A 的引用,并保留了一些旧值(我的组件是可拖动的,在这种情况下,B 将被创建 A 是当我摧毁它时)

有没有办法让 Angular 正确地销毁组件,或者至少强制它创建新的组件?

【问题讨论】:

  • 你能重现 plnkr 中的行为吗?我有this one working,但我无法(而且我真的不知道)如何重现您的问题
  • 是的,我分叉了你的 plunker:plnkr.co/edit/lvQfnLfTImcRqRcxJaXU?p=preview。单击“添加新组件”,将其拖动到某处,单击“删除”,然后再次单击“添加新组件”:组件在刚刚删除的位置创建。
  • 问题似乎是 angular2 默认重用了创建的 DOM 元素(取自 this comment)。因此,如果在您的引导程序中设置 provide(APP_VIEW_POOL_CAPACITY, {useValue: 0} 它将很好地工作。这是plnkr updated
  • 谢谢,问题解决了!您可以添加它作为答案,我会选择它。

标签: angular dynamic components dispose


【解决方案1】:

按照蒂姆的建议,

引用@tbosch 的comment

Angular 默认重用之前创建的 DOM 元素

因此,为了避免这种行为,您也可以使用 APP_VIEW_POOL_CAPACITY 并将其分配为 0 作为值。

bootstrap(MyApp, [provide(APP_VIEW_POOL_CAPACITY, {useValue: 0})])

更新

请注意,由于 beta.1 APP_VIEW_POOL_CAPACITY 已被 #5993 删除,并且 DOM 正在正确重新创建。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 2017-11-15
    • 1970-01-01
    相关资源
    最近更新 更多