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

前端之家收集整理的这篇文章主要介绍了typescript – 如何在容器中放置动态组件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想创建动态组件并将这些组件的视图插入到容器中。

我认为这可以通过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

原文链接:https://www.f2er.com/angularjs/145113.html

猜你在找的Angularjs相关文章