【问题标题】:best approach of ngFor to consider every nth elements onlyngFor 仅考虑每 n 个元素的最佳方法
【发布时间】:2020-12-01 12:15:04
【问题描述】:

使用ngFor 仅对列表的每 n 个倍数进行迭代的最佳方法是什么?目前,我将在.ts 文件中获取所有n 倍数并在ngFor 中使用它们。有没有更好的方法,比如在模板中生成这些倍数,ngFor 或任何其他更好的简化方法。

-- * .ts 文件 *--

  ngOnInit(): void {
    this.req_Indeces=[];
    this.incidentCount = this.incidentList.length;
    for(var i=0;(n*i)<this.incidentCount;i++){
      this.req_Indeces.push(n*i);
    
    }
    console.log(this.req_Indeces);
  }

-- * .html 文件 *--

            <ul *ngFor="let p of req_Indeces;let i=index; first as isFirst;let x=count">
                    <li >{{incidentList[p].src}}</li> 

                    <!-- (ignore this part if don't want to go into more details) adding rest of ele between multiples -->
                    <li >{{incidentList[p].src}}</li>
                    <li >{{incidentList[(p+1)%(n*x)].src}}</li>
                    <li >{{incidentList[(p+2)%(n*x)].src}}</li>
                    .
                    <li >{{incidentList[(p+(n-1))%(n*x)].src}}</li>
                                                                                       
            </ul>

更多限制:

  • 使用ngIf 并且跳过不是一种选择,因为它会在要显示的请求列表之间给出空列表。
  • 为简单起见,我认为incidentCount,n 是均匀的。

【问题讨论】:

    标签: angular ngfor


    【解决方案1】:

    构建一个新数组(通过复制您要查看的元素)通常被认为比仅通过索引访问它们要慢,因此构建您要显示的索引数组应该更快。像这样:

    indexList = [...Array(this.list.length).keys()].filter(i => i % 2 == 0);
    

    显示它:

    <li *ngFor="let elm of indexList">{{list[elm]}}</li>
    

    在这里你也有一个堆栈闪电战:https://stackblitz.com/edit/angular-ivy-rykafe?file=src%2Fapp%2Fapp.component.html

    您可以将其打包成可重用的指令(参见 stackblitz):

    <li *myForNth="let elm of list;n: 2">{{elm}}</li>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 2019-02-20
      • 2018-05-24
      相关资源
      最近更新 更多