Angular2动态引用并创建Component

时间:2016-10-23 02:58:29

标签: angular dynamic reference angular2-components

例如,我在一个组件中有一个选项列表,其中单击一个组件会根据用户的选择动态呈现组件。这就是我想象的方式:

列出组件

import { Component } from '@angular/core';
@Component({
    selector: 'list-component',
    templateUrl: `
        <ul>
            <li *ngFor="let item from list" (click)="onClick(item)">{{item.name}}</li>
        </ul>
    `
})
export class ListComponent {

    list = [
        {name: 'Component1'},
        {name: 'Component2'},
        {name: 'Component3'}
    ]

    constructor(private _listService: ListService) {

    }

    onClick(item) {
        this._listService.renderComponent(item);
    }
}

渲染组件

import { Component, ViewContainerRef } from '@angular/core';

@Component({
    selector: 'render-component',
    templateUrl: `
        <div #dynamicComponent></div>
    `
})
export class RenderComponent {

    @ViewChild('dynamicComponent', { read: ViewContainerRef })
    private dynamicComponent: any;

    constructor(
        private _listService: ListService,
        private resolver: ComponentFactoryResolver
    ) {

        this._listService.onRenderComponent.subscribe(item => {
            let componentReference;

            //TODO: Get Component by reference ???

            let componentFactory = this.resolver.resolveComponentFactory(componentReference);
            this.dynamicComponent.createComponent(componentFactory);

        })
    }
}

我已经留下了有关ListService的详细信息,但它本质上是一项允许两个组件进行通信的服务。

我不希望像List中那样引用ListComponent中的组件:

import {Component1, Component2, Component3} from './otherComponents';

...

list = [
    {name: 'Component1', component: Component1},
    {name: 'Component2', component: Component2},
    {name: 'Component3', component: Component3}
]

...

this._listService.onRenderComponent.subscribe(item => {
    let componentReference = item.component;

    let componentFactory = this.resolver.resolveComponentFactory(componentReference);
    this.dynamicComponent.createComponent(componentFactory);

})

让ListService处理它。

从本质上讲,angular是否提供了基于某些引用来检索Component的方法,例如selectorcomponentId或沿着这些行的某些内容?

1 个答案:

答案 0 :(得分:1)

如果你使用Angular 2.0 final(我认为你不是),你可以通过选择器实际解析组件。

 const compFactory = this.factory.componentFactories.find(x => x.selector === 'my-component-selector');
    const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
    const cmpRef = this.vcRef.createComponent(compFactory, this.vcRef.length, injector, []);

我有动态组件创建的简约示例here

相关问题