Angular2:将动态组件作为容器的子代插入到DOM中

有没有办法在Angular 2中动态插入一个组件作为一个DOM标签的子(而不是兄弟)?

有很多例子可以将一个动态组件作为给定的ViewContainerRef标签的兄弟插入,如(从RC3开始):

@Component({
  selector: '...',template: '<div #placeholder></div>'
})
export class SomeComponent {
  @ViewChild('placeholder',{read: ViewContainerRef}) placeholder;

  constructor(private componentResolver: ComponentResolver) {}

  ngAfterViewInit() {
    this.componentResolver.resolveComponent(MyDynamicComponent).then((factory) => {
        this.componentRef = this.placeholder.createComponent(factory);
    });
  }
}

但是这会产生类似于以下的DOM:

<div></div>
<my-dynamic-component></my-dynamic-component>

预期结果:

<div>
    <my-dynamic-component></my-dynamic-component>
</div>

使用SomeComponent的ViewContainerRef具有相同的结果,它仍然将生成的组件作为兄弟,而不是子进程插入.我可以使用一个解决方案,其中模板是空的,动态组件插入到模板中(在组件选择器标签中).

当使用像ng2-dragula这样的库从动态组件和benefit from the model updates的列表中拖动时,DOM结构非常重要.额外的div在可拖动元素的列表中,但在模型之外,打破了drag&放弃逻辑.

有人说这是不可能的(c.f. this comment),但这听起来是一个非常令人惊讶的限制.

为Angular 2发行编辑

TL; DR:替换< div#placeholder>< / div>由< div>< template#placeholder>< / template>< / div>插入div内.

这是一个working plunker与创建动态组件的新方法.

这是一个很长的时间,而不是增加价值的问题,所以我不会在这里复制代码.

编辑2

看来< ng-container#placeholder>< / ng-container>也在工作.我喜欢这种方法,因为< ng-container>明确地针对这个用例(一个添加标签的容器),并且可以在其他情况下使用,如NgIf,而不用真正的标签包装.

原来的答案

@GünterZöchbauer在评论中指示我进行正确的讨论.我回答自己的问题:替换< div#placeholder>< / div>由< template#placeholder>< / template&gt ;. 所以这个例子变成:

@Component({
  selector: 'my-app',template: '<template #placeholder></template>'
})
export class AppComponent {
  @ViewChild('placeholder',{read: ViewContainerRef}) placeholder;

  constructor(private componentResolver:ComponentResolver) {}

  ngAfterViewInit() {
    this.componentResolver.resolveComponent(MyDynamicComponent).then((factory) => {
        this.componentRef = this.placeholder.createComponent(factory);
    });
  }
}

Plunker

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...