我想创建动态组件并将这些组件的视图插入到容器中.
I want to create dynamic components and insert views of these components to a container.
我认为可以通过 ViewContainerRef
但是我不知道,我们可以获取任何组件的ViewContainerRef吗?如果是,那么如何? 我是Angular的新手,如果有任何其他好的解决方案可以解决这种情况,请提出建议.
But I don't know, can we get ViewContainerRef of any component? if yes then how?. I am new to Angular, if there are any other good solutions available to handle this scenario, please suggest me.
已更新 我认为,我已经很接近解决方案了.下面是代码.
Updated I think, I am pretty much near to the solution. Below is the code.
appponent.ts
appponent.ts
import {Component} from '@angular/core'; import {ContainerComponet} from './containerponent' @Component({ selector: 'my-app', template: ` <container> </container> `, directives: [ContainerComponet] }) export class AppComponent { constructor() { } }containerponent.ts
containerponent.ts
import {Component, ComponentResolver, ViewContainerRef} from '@angular/core' import {controlBoxComponent as controlBox} from './controlBoxponent'; @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, 0, ctxInjector); }) } }controlBoxponent.ts
controlBoxponent.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
You can get the ViewContainerRef of the current component by or from an element in the view of the current component
@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 = thisponentFactoryResolver.resolveComponentFactory(ControlBox) thisponentRef = this.other.createComponent(factory); // thisponentRef = this.foo.createComponent(factory); // thisponentRef = this.div.createComponent(factory); // thisponentRef = this.viewContainerRef.createComponent(factory); }); }另请参见 Angular 2动态标签用户单击选定的组件
更多推荐
如何在容器中放置动态组件
发布评论