如何让数据显示在正确的位置

test[
    ["good1","1"],
    ["good2","2"],
    ["good3","3"],
    ["good4","4"]
]

一段数据如上,它是会变动的,但不会超过四个

例如有时候可能是

test[
    ["good1","1"],
    ["good2","2"],
    ["good4","4"]
]


然后我在页面上做了四个框框放这四个资料,

clipboard.png

代码大概长这样子

    <div class="container">
     <div>
        <ng-container *ngIf="test[0]">
            <span>{{test[0][0]}}</span>
        </ng-container>
     </div>
     <div>
        <ng-container *ngIf="test[1]">
            <span>{{test[1][0]}}</span>
        </ng-container>
     </div>
     <div>
        <ng-container *ngIf="test[2]">
            <span>{{test[2][0]}}</span>
        </ng-container>
     </div>
     <div>
        <ng-container *ngIf="test[3]">
            <span>{{test[3][0]}}</span>
        </ng-container>
     </div>
     
    </div>


每个数据都要放在固定的位置

问题来了,数据有四个没问题,但是如果今天数据只有三个,第三个位置今天没数据

画面会变成

clipboard.png

第四个数据就跑到第三个数据的位置上了,因为数组剩三个,第四个往上移了,我抓第三个会变抓第四个

test[
        ["good1","1"],
        ["good2","2"],
        ["good4","4"]
    ]

我想要每个数据都在正确的位置,第四个就应该在第四个,然后第三个位置就空着

這该如何做到?

阅读 1.7k
1 个回答

外层做循环,这样无所谓你以后会不会多少数据:

<div class="container">
    <div *ngFor="let good of test">
        <ng-container *ngIf="good[0]">
            <span>{{good[0]}}</span>
        </ng-container>
     </div>
</div>

拿到原始数据可以自己处理一下,不足的位置里补上空数组,可以做成通用的处理。
如果以后不再扩展只有4个的话,那就只需要在数据里补上一个空的就好了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题