Dynamically bind model and template to at DOM node in Angular 2

若如初见. 提交于 2019-12-03 13:58:43

Short version

see https://github.com/angular/angular/issues/2753 (the recent comments, not the original issue)


Long version

I have a similar use-case and have been keeping an eye on chatter about recommended approaches to it.

As of now, DynamicComponentLoader is indeed the de-facto tool for dynamic component compilation (read: stand-in for $compile) and the approach you've taken in your example is essentially identical to this one, which @RobWormald has posted in response to several similar questions on gitter.

Here's another interesting example @EricMartinez gave me, using a very similar approach.

But yes, this approach feels clunky to me too, and I've yet to find (or come up with) a more elegant way of doing this with DCL. The comments on the github issue I linked above contain a third example of it, along with similar criticisms that have so far gone unsanswered.

I have a hard time believing that the canonical solution for a use-case as common as this will be so clunky in the final release (particularly given then relative elegance of $compile), but anything beyond that would be speculation.

If you grep "DCL" or "DynamicComponentLoader" in the gitter thread, there are several interesting conversations on this topic there. One of the core team guys said something to the effect of "DCL is a power-tool that we only expect will be used by people doing really framework-ey things" - which I found... interesting.

(I'd have quoted/linked to that directly if gitter's search didn't suck)

The correct behavior can be achieved with minor changes in your code: you have to "dispose" the previously created component before adding a new one.

savedComp: Component = null;
...
if (this.savedComp) {
  this.savedComp.dispose();
}
this.loader.loadIntoLocation(DynamicComponent, this.element, 'attach')
    then((res) => {res.instance.model = model; this.savedComp = res;});

Full solution here: http://plnkr.co/edit/KQM31HTubn0LfL7jSP5l

Hope it helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!