我想创建动态组件并将这些组件的视图插入到容器中。
我认为这可以通过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
原文链接:https://www.f2er.com/angularjs/145113.html@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); }); }