加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 09:28:04 所属栏目:安全 来源:网络整理
导读:有没有办法在Angular 2中动态插入一个组件作为一个DOM标签的子(而不是兄弟)? 有很多例子可以将一个动态组件作为给定的ViewContainerRef标签的兄弟插入,如(从RC3开始): @Component({ selector: '...',template: 'div #placeholder/div'})export class SomeC
有没有办法在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读