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

typescript – 如何在容器中放置动态组件

发布时间:2020-12-17 08:26:10 所属栏目:安全 来源:网络整理
导读:我想创建动态组件并将这些组件的视图插入到容器中。 我认为这可以通过ViewContainerRef实现。 但是我不知道,我们可以得到任何组件的ViewContainerRef吗?如果是,那么怎么样? 如果有其他好的解决方案可以处理这种情况,我是新手角色的,请建议我。 更新 我
我想创建动态组件并将这些组件的视图插入到容器中。

我认为这可以通过ViewContainerRef实现。

但是我不知道,我们可以得到任何组件的ViewContainerRef吗?如果是,那么怎么样?
如果有其他好的解决方案可以处理这种情况,我是新手角色的,请建议我。

更新
我觉得我很接近解决方案。下面是代码。

app.component.ts

import {Component} from '@angular/core';
import {ContainerComponet} from './container.component'

@Component({
    selector: 'my-app',template: `
    <container> </container>
    `,directives: [ContainerComponet]
})
export class AppComponent {

    constructor() { }

 }

container.component.ts

import {Component,ComponentResolver,ViewContainerRef} from '@angular/core'
import {controlBoxComponent as controlBox} from './controlBox.component';

@Component({
    selector: 'container',template: 'container'    
})
export class ContainerComponet {
    constructor(viewContainer: ViewContainerRef,private _cr: ComponentResolver) {

        this._cr.resolveComponent(controlBox)
            .then(cmpFactory => {
                const ctxInjector = viewContainer.injector;
                return viewContainer.createComponent(cmpFactory,ctxInjector);
            })

    }
}

controlBox.component.ts

import {Component} from '@angular/core'
@Component({
    selector: 'controlBox',template: 'controlBox'
})
export class controlBoxComponent {
    constructor() { }
}

输出

<my-app>
    <container>container</container><controlbox _ngcontent-lsn-3="">controlBox</controlbox>
</my-app>

预期结果

<my-app>
    <container>container
    <controlbox _ngcontent-lsn-3="">controlBox</controlbox>
    </container>
</my-app>
您可以通过当前组件的视图中的元素获取当前组件的ViewContainerRef
@Component({
  selector: '...',directives: [OtherComponent,FooComponent],template: `
    <other-component></other-component>
    <foo-component #foo></foo-component>
    <div #div></div>`
})

export class SomeComponent {
  // `ViewContainerRef` from an element in the view
  @ViewChild(OtherComponent,{read: ViewContainerRef}) other;
  @ViewChild('foo',{read: ViewContainerRef}) foo;
  @ViewChild('div',{read: ViewContainerRef}) div;

  // `ViewContainerRef` from the component itself
  constructor(private viewContainerRef:ViewContainerRef,private componentFactoryResolver: ComponentFactoryResolver) {}

  let factory = this.componentFactoryResolver.resolveComponentFactory(ControlBox)
  this.componentRef = this.other.createComponent(factory);
  // this.componentRef = this.foo.createComponent(factory);
  // this.componentRef = this.div.createComponent(factory);
  // this.componentRef = this.viewContainerRef.createComponent(factory);
  });
}

参见Angular 2 dynamic tabs with user-click chosen components

(编辑:李大同)

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

    推荐文章
      热点阅读