在运行时将新的Component元素添加到Angular 2中的DOM中不会渲染该组件 [英] Adding new Component element to DOM in Angular 2 at runtime doesn't render the component

查看:39
本文介绍了在运行时将新的Component元素添加到Angular 2中的DOM中不会渲染该组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在运行时动态添加DOM中的新节点.新节点基本上是组件选择器.问题在于该组件的内容未呈现,因此结果只是具有空的HTML标记.

我正在使用Angular 2.0文档示例,并对其进行了一些修改,只是为了展示案例.

解决方案

createComponent()版本:柱塞

  this.resolver.resolveComponent(HeroListComponent).then((factory:ComponentFactory< any>)=> {this.cmpRef = this.theBody.createComponent(factory)}); 

具有 .loadNextToLocation()

beta.17(不建议使用)版本:柱塞(已弃用)

  addCmp(){console.log('adding');this.dcl.loadNextToLocation(HeroListComponent,this.theBody);} 

您不是在创建组件,而是在创建html元素并将其附加到恰好与组件选择器具有相同名称的DOM上.

为了实现您想要的目标,您必须使用DynamicComponentLoader .

I'm trying to add dynamically (at runtime) new nodes in the DOM. The new nodes basically are the Component selectors. The problem is that the content of the component is not rendered so the result is just having empty HTML tags.

I'm using Angular 2.0 Documentation example and modified it a little bit just to show case.

Here is the plunker

All I do is to reuse the code and when I click on the body to create new sales-tax elements. Obviously it's not working.

This is the new script element I added ontop of body.

<script>
  function add(){
     var element = document.createElement('sales-tax');
    document.getElementsByTagName("my-app")[0].appendChild(element);
  }
</script>

and the function is invoked once I click the body.

 <body onclick="add()">
    <my-app>Loading...</my-app>
 </body>

This is the result. As you can see the sales-tax that has been added to the template pre runtime it's rendered but the ones that I add at runtime are empty.

解决方案

createComponent() version: Plunker

this.resolver.resolveComponent(HeroListComponent).then((factory:ComponentFactory<any>) => {
      this.cmpRef = this.theBody.createComponent(factory)
    });

beta.17 (deprecated) version with .loadNextToLocation(): Plunker(deprecated)

 addCmp(){
    console.log('adding');
    this.dcl.loadNextToLocation(HeroListComponent, this.theBody);
  }

You are not creating a component you are just creating an html element and appending it to the DOM which happens to have the same name with a components selector.

In order to achieve what you want you have to use DynamicComponentLoader.

这篇关于在运行时将新的Component元素添加到Angular 2中的DOM中不会渲染该组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆