微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/angularjs/140661.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐