【问题标题】:Angular2 dynamically reference and create ComponentAngular2动态引用和创建组件
【发布时间】:2016-10-23 14:59:41
【问题描述】:

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

列表组件

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 的详细信息,但它本质上是一个允许两个组件通信的服务。

我不希望像这样引用 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 是否提供了基于某些引用(例如 selectorcomponentId 或类似的东西)检索组件的方法?

【问题讨论】:

标签: angular dynamic reference angular2-components


【解决方案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

【讨论】:

  • 好像他不使用Compiler 他更喜欢将ComponentFactoryResolverentryComponentsANALYZE_FOR_ENTRY_COMPONENTS 提供程序一起用于动态组件创建。
  • 很公平。那已经被弃用了吗?我说不出来。
猜你喜欢
  • 1970-01-01
  • 2017-11-01
  • 2017-07-21
  • 2016-08-02
  • 2017-04-27
  • 1970-01-01
  • 2017-08-26
相关资源
最近更新 更多