我正在Angular 2(和TypeScript)中构建一个模态组件,它将具有不同的视图/页面.它没有标签,但概念非常相似.基本上我正在努力寻找这样做的方法.
在我的模态组件中,我想输出不同的视图/页面.每个都应该是一个组件本身,因为它们没有任何共同的标记.另外,它们将从服务类中获取数据,因此我需要能够为每个视图编写特定的逻辑.
基本上我想要的是:
// Within my modal component's template
<div *ngFor="#view of views">
// Render view component here
</div>
Run Code Online (Sandbox Code Playgroud)
例如,哪里views可以是组件的数组.我的第一个主要问题是我不确定如何输出我的视图(组件)的集合.
如何在另一个组件中输出组件集合?
此外,我需要一种隐藏和显示视图的方法,这是视图唯一的共同点.我正在考虑isActive在视图中添加一个变量,并根据它显示/隐藏它们.视图组件实现ModalView接口或从基类扩展以添加此逻辑是不好的做法?从我的模态分量,我希望能够控制显示哪个观点,所以我需要的意见,有共同的这个逻辑.
我希望很清楚我想做什么.解决方案可能很简单,但是现在我对如何解决这个问题感到有些困惑.一个代码示例将非常感谢!
您可以创建一个“组件工厂”作为指令,根据您从模态传递的参数,使用DynamicComponentLoader加载适当的组件。
<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)
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7432 次 |
| 最近记录: |