【发布时间】:2020-01-05 10:24:44
【问题描述】:
我正在为元素列表构建一个具有一致设计模式的应用。如果我有一个 A 类型的对象,我将创建 AComponent,它接受 a 作为输入,然后创建另一个组件来遍历 A 的列表 AListComponent。然后,如果我有一个对象 B,我需要做同样的事情。似乎我应该能够在我想要迭代的对象的类中创建一个ObjectListComponent,以保持我的代码干燥。
例如,给定
组件控制器
...
@Input
a: A;
...
组件 HTML
<div>{{ a.name }}</div>
AListComponent 控制器
...
@Input()
aList: A[];
...
AListComponent HTML
<div *ngFor='let aObj of aList'>
<app-a [a]='aObj'></app-a>
</div>
我们如何将AListComponent 抽象为ObjectListComponent?
ObjectListComponent 控制器
...
@Input()
type: any;
@Input()
objects: <type>[]
objectComponent: any;
ngOnInit () {
this.objectComponent = <get object component from type>
}
ObjectListComponent HTML
<div *ngFor='let obj of objects'>
<app-objectComponent [object]='obj'></app-objectComponent>
</div>
ObjectListComponent 将被用作
...
<app-object-list [type]='A' objects='aList'></app-object-list>
...
【问题讨论】:
-
您需要提供更多信息。
AComponent与BComponent有多少差异?我的意思是,它们都相似吗(css,函数)?this.objectComponent的用途是什么,你打算如何使用它?如果唯一的区别是type,则创建接口ICanvasComponentInput,并在其中定义类型为obj: A | B。在ObjectListComponent@Input参数中使用它。 (尝试为 ObjectListComponent 提供更通用的名称) -
这个想法是
ObjectListComponent应该能够迭代任意模型列表,因为表示模型的组件是通过type属性传入的。this.objectComponent将是表示通过objects属性传入的对象列表中的对象类型的组件。 -
我想我得到了一点问题。如果您可以在 stackblitz.com 上创建一个演示,这对我真的很有帮助。我会从那里拿走它
-
表示找不到请求的页面
-
对不起,我之前没用过StackBlitz,所以还是习惯了。这应该工作:stackblitz.com/github/bicarlsen/temp
标签: javascript html angular typescript