在Angular 2中输出组件数组 [英] Outputting array of components in Angular 2
问题描述
我正在Angular 2(和TypeScript)中构建一个模态组件,该组件将具有不同的视图/页面.它没有选项卡,但是概念非常相似.基本上,我正在努力寻找一种方法来做到这一点.
I am building a modal component in Angular 2 (and TypeScript) that will have different views/pages. It won't have tabs, but the concept is pretty similar. Basically I am struggling to find an approach to doing this.
在我的模式组件中,我想输出不同的视图/页面.每个组件本身都应该是一个组件,因为它们没有任何共同的标记.另外,它们将从服务类中获取数据,因此我需要能够为每个视图编写特定的逻辑.
Within my modal component, I want to output the different views/pages. Each one should be a component itself, because they don't have any markup in common. Plus, they will fetch data from service classes, so I need to be able to write specific logic for each view.
基本上我想要的是这样的
Basically what I want is something like:
// Within my modal component's template
<div *ngFor="#view of views">
// Render view component here
</div>
例如,其中views
可以是组件的数组.我的第一个也是主要的问题是我不确定如何输出我的视图(组件)的集合.
Where views
could be an array of the components, for instance. My first and main problem is that I am not sure how to output a collection of my views (components).
如何在另一个组件中输出一组组件?
How can I output a collection of components within another component?
此外,我需要一种隐藏和显示视图的方法,这是视图唯一的共同点.我当时正在考虑在视图中添加一个isActive
变量,并基于此显示/隐藏它们.视图组件要么实现ModalView
接口,要么从基类扩展以添加此逻辑,这是不好的做法吗?从我的模式组件中,我希望能够控制显示哪个视图,因此我需要这些视图具有相同的逻辑.
Also, I need a way to hide and show views, which is the only thing the views have in common. I was thinking of adding an isActive
variable to the views and showing/hiding them based on that. Would it be bad practice for the views components to either implement a ModalView
interface or extend from a base class to add this logic? From my modal component, I want to be able to control which view is displayed, so I need the views to have this logic in common.
我希望很清楚我想做什么.解决方案可能很简单,但是现在我对如何解决感到有些困惑.一个代码示例将不胜感激!
I hope it is clear what I want to do. The solution may be simple, but right now I am a bit confused on how to go about it. A code example would be much appreciated!
推荐答案
You can create a "component factory" as a directive that loads appropriate components using DynamicComponentLoader, based on parameters you pass from your modal.
<component-factory *ngFor="#view of views"
(loaded)="addComponent($event)"
[name]="view.name"
[visible]="view.visible"></component-factory>
@Directive({ selector: 'component-factory' })
class ComponentFactory {
@Input() name;
@Input() visible;
@Output() loaded = new EventEmitter();
constructor(
private _dcl: DynamicComponentLoader,
private _eref: ElementRef) {
// import OneCmp, TwoCmp in this file...
private components: { one: OneCmp, two: TwoCmp }
ngOnInit() {
this._dcl.loadNextToLocation(
this.components[this.name],
this._eref)
// pass values to the loaded components
// and send it's instance to the parent
.then((ref: ComponentRef) => {
ref.instance.visible = this.visible;
this.loaded.emit(ref.instance)
});
}
}
这篇关于在Angular 2中输出组件数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!