且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

角度2 - 即时添加/删除组件

更新时间:2023-12-05 22:14:52

正如蒂姆所建议的,



引用@ tbosch的评论


默认情况下,重复使用以前创建的DOM元素


所以为避免这种行为,您也可以使用 APP_VIEW_POOL_CAPACITY 并将其分配为$ code> 0 作为值引导程序(MyApp,[提供(APP_VIEW_POOL_CAPACITY,{useValue:0})])



更新



请注意,自从beta #5993 删除了 APP_VIEW_POOL_CAPACITY ,DOM正在重新正确。


I need to be able to add & remove angular 2 components on the fly. To do so, I'm using loadIntoLocation and dispose methods, like it:

Adding a component (from a layout manager):

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

Removing a component (from the component):

this.ref.dispose();

It is nearly working: - if I add a component, and close it, it works - if I add several components, they work - but if I add component A, then remove it, then add component B, it seems like Angular gives me a reference to A, and keeps some old values (my components are draggable, and in this case the B will be created A was when I destroyed it)

Is there a way to make Angular destroy components properly, or at least to force it to create fresh ones?

As suggested by Tim,

quoting @tbosch's comment

Angular reuses previously created DOM elements by default

So to avoid this behavior, taken from the comment as well, you can use APP_VIEW_POOL_CAPACITY and assign it 0 as value.

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

Update

Note that since beta.1 APP_VIEW_POOL_CAPACITY was removed by #5993 and the DOM is being recreated correctly.