如何更新 angular 2 中的 ElementRef?
How to update ElementRef in angular 2?
我在使用 dynamicComponentloader
加载组件时遇到问题。我有一个父组件和三种子组件。
首先我使用Interact.js将子组件A和子组件B拖到父组件中。显示如下
Component A
Component B
我使用的方法是loadIntoLocation(.., elementRef, ..)
。然后我通过 DOM 像这样操作
来改变他们的位置
Component B
Component A
改变位置后,我将第三个组件拖到父组件中,我认为它应该插入到父组件的底部,如下所示
Component B
Component A
Component C
但实际上第三个组件插入到componentA和componentB的位置
Component B
Component C
Component A
我已经把这个例子制作成plnkr here.
我认为导致此问题的原因是我更改了 DOM,但没有将更改映射到 elementRef
。所以我正在寻找更新 elementRef
的方法,希望它能解决我的问题。
有任何解决此问题的建议或以 angular 方式更改两个组件位置的任何解决方案吗?
我玩这个有一段时间了
首先,我持有被注入组件的引用,以便稍后使用它们
instances : [] = [];
addAB(){
this.loader.loadIntoLocation(ComponentA, this.elementRef, "container")
.then((r) => this.instances.push(r));
this.loader.loadIntoLocation(ComponentB, this.elementRef, "container")
.then((r) => this.instances.push(r));
}
loadIntoLocation
returns a Promise which resolves to ComponentRef
,这就是我持有的数组。
现在,当我们交换它们时,我拿了第一个,重新插入它,当它正确解析时,我删除了第一个引用。更清楚:插入A和B,再次插入A,删除第一个A。
changePosition(){
// Take the first one
let first = this.instances[0];
// Reinsert the first one
this.loader.loadIntoLocation(first.hostComponentType, this.elementRef, "container")
.then((_) => first.dispose()); // dispose() destroys the previous instance
}
这就是您所需要的。插入 ComponentC 是一样的,不需要改变。就像我在 gitter 中告诉你的那样,我认为它在内部跟踪位置并且你在 angular2 不知道的情况下操纵 DOM (这纯粹是基于其行为的猜测,显然需要调查)。所以这是我得到的最angular2的方法,希望对你有帮助。
这是一个 plnkr 你的案例。
我在使用 dynamicComponentloader
加载组件时遇到问题。我有一个父组件和三种子组件。
首先我使用Interact.js将子组件A和子组件B拖到父组件中。显示如下
Component A
Component B
我使用的方法是loadIntoLocation(.., elementRef, ..)
。然后我通过 DOM 像这样操作
Component B
Component A
改变位置后,我将第三个组件拖到父组件中,我认为它应该插入到父组件的底部,如下所示
Component B
Component A
Component C
但实际上第三个组件插入到componentA和componentB的位置
Component B
Component C
Component A
我已经把这个例子制作成plnkr here.
我认为导致此问题的原因是我更改了 DOM,但没有将更改映射到 elementRef
。所以我正在寻找更新 elementRef
的方法,希望它能解决我的问题。
有任何解决此问题的建议或以 angular 方式更改两个组件位置的任何解决方案吗?
我玩这个有一段时间了
首先,我持有被注入组件的引用,以便稍后使用它们
instances : [] = [];
addAB(){
this.loader.loadIntoLocation(ComponentA, this.elementRef, "container")
.then((r) => this.instances.push(r));
this.loader.loadIntoLocation(ComponentB, this.elementRef, "container")
.then((r) => this.instances.push(r));
}
loadIntoLocation
returns a Promise which resolves to ComponentRef
,这就是我持有的数组。
现在,当我们交换它们时,我拿了第一个,重新插入它,当它正确解析时,我删除了第一个引用。更清楚:插入A和B,再次插入A,删除第一个A。
changePosition(){
// Take the first one
let first = this.instances[0];
// Reinsert the first one
this.loader.loadIntoLocation(first.hostComponentType, this.elementRef, "container")
.then((_) => first.dispose()); // dispose() destroys the previous instance
}
这就是您所需要的。插入 ComponentC 是一样的,不需要改变。就像我在 gitter 中告诉你的那样,我认为它在内部跟踪位置并且你在 angular2 不知道的情况下操纵 DOM (这纯粹是基于其行为的猜测,显然需要调查)。所以这是我得到的最angular2的方法,希望对你有帮助。
这是一个 plnkr 你的案例。