【发布时间】: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 是否提供了基于某些引用(例如 selector、componentId 或类似的东西)检索组件的方法?
【问题讨论】:
标签: angular dynamic reference angular2-components