Angular2动态地引用和创建组件



例如,我在一个组件中有一个选项列表,单击其中一个将根据用户的选择动态地呈现一个组件。我认为应该这样做:

列表组件

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);
    }
}
<<p> 渲染组件/strong>
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的细节,但它本质上是一个允许两个组件通信的服务。

我不喜欢在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处理它

所以本质上,角提供的方法检索一个组件基于一些引用,如selector, componentId或沿着这条线?

如果你使用的是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, []);

我这里有一个动态组件创建的极简示例

相关内容

  • 没有找到相关文章

最新更新