在Angular中对组件进行排序

8
我需要在下面的模板中动态排序组件。
<div class="orderList">
    <componentA></componentA>
    <componentB></componentB>
    <componentC></componentC>
</div>

按对象类型
orders: {
    componentA: 2,
    componentB: 3,
    componentC: 1
}

我期望首先看到 componentC,然后是 componentA,最后是 componentB。注意:组件数量超过三个。

为什么不立即在您的根组件中对它们进行排序?请给我们更多上下文。 - Christopher
您是否希望按特定顺序呈现它们? - Drag13
@Christopher 在下订单后,我需要先收到 componentC 组件,然后是 componentA 和 componentB。 - fingerpich
1
如果您像 https://dev59.com/iFoV5IYBdhLWcg3wY976#36325468 中所示的添加组件,那么您只需要在数组中重新排序组件类型即可。 - Günter Zöchbauer
1
谢谢@GünterZöchbauer。我已经根据您的有用评论添加了一个答案。但我认为这个简单问题可能有更简单的答案。 - fingerpich
显示剩余4条评论
2个回答

10
使用CSS的flex顺序属性
<div style="display:flex;">
   <componentA [style.order]="orders.componentA"></componentA>
   <componentB [style.order]="orders.componentB"></componentB>
   <componentC [style.order]="orders.componentC"></componentC>
</div>

我只想补充一句,为了改变方向,您可以使用 display:flex; flex-direction: column;(默认情况下,子组件是排成一行的)。 - Jake_3H
在这个问题上,你必须注意无障碍性。对于视觉障碍用户,制表顺序必须是直观的。更多信息请参见:https://dev59.com/s6Lia4cB1Zd3GeqPfzy9 - mmokrzycki

1

正如@GünterZöchbauer在评论中建议的那样,这个答案使用ngComponentOutlet来动态排序组件。

<ng-container 
    *ngFor="item in sortedComponent" 
    *ngComponentOutlet="item.component">
</ng-container>

sortedComponent = [
    {index: 4, component: 'componentA'},
    {index: 5, component: 'componentB'},
    {index: 2, component: 'componentC'},
].sort((a, b) => a.index > b.index)

item.component中的component是什么?它是一个组件指令吗? - WasiF
item.component 是你定义的组件名称。 - fingerpich
当您创建了组件对象后,为什么还需要再次添加组件类名称。这看起来是不合逻辑的。 - WasiF
假设您有一个组件类名为 myComponent,那么它应该如何被调用?根据您的理解(我所理解的),是 item.myComponent,对吗? - WasiF
我刚刚更新了答案,并添加了更多关于我所做的事情的细节。 - fingerpich
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接