Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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

大佬总结

以上是大佬教程为你收集整理的Angular2:将动态组件作为容器的子代插入到DOM中全部内容,希望文章能够帮你解决Angular2:将动态组件作为容器的子代插入到DOM中所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。