【问题标题】:How can I limit ngFor repeat to some number of items in Angular?如何将 ngFor 重复限制为 Angular 中的某些项目?
【发布时间】:2016-10-15 13:54:21
【问题描述】:

我的代码:

<li *ngFor="let item of list; let i=index" class="dropdown-item" (click)="onClick(item)">
  <template [ngIf]="i<11">{{item.text}}</template>
</li>

我试图在任何时候只显示 10 个列表元素。正如answer here 中所建议的那样,我使用了 ngIf,但这会导致页面上显示空列表项(超过 10 个)。

【问题讨论】:

    标签: angular


    【解决方案1】:

    这对我来说似乎更简单

    <li *ngFor="let item of list | slice:0:10; let i=index" class="dropdown-item" (click)="onClick(item)">{{item.text}}</li>
    

    更接近你的方法

    <ng-container *ngFor="let item of list; i as index">
      <li class="dropdown-item" (click)="onClick(item)" *ngIf="i<11">{{item.text}}</li>
    </ng-container>
    

    另类

    <ng-template ngFor let-item [ngForOf]="list" let-i="index">
      <li class="dropdown-item" (click)="onClick(item)" *ngIf="i<11">{{item.text}}</li>
    </ng-template>
    

    【讨论】:

    • 第二种方法为您提供更好的 UI 灵活性。即 *ngIf="i
    • 嗨,假设数组有 12 个项目,我们将 3 切片...如何获取剩余部分以便在其他地方显示(例如在按钮中:剩下 9 个项目)跨度>
    • slice:0:10 会影响原始数组吗??
    • slice 返回一个副本,不影响原始数组
    • | slice:0:10 管道很棒,它帮助我构建了一个带有“查看更多”按钮的列表,该按钮增加了slices 的第二个参数。
    【解决方案2】:

    您可以通过应用三元运算符来动态限制*ngFor

    示例 1 -

    <div *ngFor="let item of (showAllFlag ? list : list.slice(0,2))" >
    </div>
    

    【讨论】:

      【解决方案3】:

      我发现下面是个好方法

      <ul class="list-group col-auto" *ngFor="let result of searchResults.slice(0,10)">
                          <li class="list-group-item">
                              <b>{{result.name}}</b>
                              <p>{{result.email}}</p>
                              <p>{{result.body | slice:0:64}}</p>
                          </li>
                      </ul>
      

      【讨论】:

        【解决方案4】:
         <div *ngFor="let item of list;trackBy: trackByFunc" >
           {{item.value}}
         </div>
        

        在你的 ts 文件中

         trackByFunc(index, item){
            return item ? item.id : undefined;
          }
        

        【讨论】:

          【解决方案5】:

          例如,假设我们只想显示数组的前 10 项,我们可以使用 SlicePipe 来做到这一点,如下所示:

          <ul>
               <li *ngFor="let item of items | slice:0:10">
                {{ item }}
               </li>
          </ul>
          

          【讨论】:

          • 谢谢,我在 angular 12 中使用这个解决方案
          【解决方案6】:

          html

          <table class="table border">
              <thead>
                  <tr>
                      <ng-container *ngFor="let column of columns; let i = index">
                          <th>{{ column }}</th>
                      </ng-container>
                  </tr>
              </thead>
              <tbody>
                  <tr *ngFor="let row of groups;let i = index">
                      <td>{{row.name}}</td>
                      <td>{{row.items}}</td>
                      <td >
                          <span class="status" *ngFor="let item of row.Status | slice:0:2;let j = index">
                              {{item.name}}
                             </span><span *ngIf = "i < 2" class="dots" (mouseenter) ="onHover(i)" (mouseleave) ="onHover(-1)">.....</span> <span [hidden] ="test" *ngIf = "i == hoverIndex" class="hover-details"><span  *ngFor="let item of row.Status;let j = index">
                              {{item.name}}
                             </span></span>
                     </td>
          
                  </tr>
            </tbody>
          </table>
          
          <p *ngFor="let group of usersg"><input type="checkbox" [checked]="isChecked(group.id)" value="{{group.id}}" />{{group.name}}</p>
          
          <p><select [(ngModel)]="usersr_selected.id">
             <option *ngFor="let role of usersr" value="{{role.id}}">{{role.name}}</option> 
          </select></p>
          

          打字稿

          import { Component, OnInit } from '@angular/core';
          import { CommonserviceService } from './../utilities/services/commonservice.service';
          import { FormBuilder, FormGroup, Validators } from '@angular/forms';
          @Component({
            selector: 'app-home',
            templateUrl: './home.component.html',
            styleUrls: ['./home.component.css']
          })
          export class HomeComponent implements OnInit {
            getListData: any;
           dataGroup: FormGroup;
           selectedGroups: string[];
              submitted = false;
              usersg_checked:any;
              usersr_selected:any;
              dotsh:any;
              hoverIndex:number = -1;
              groups:any;
              test:any;
           constructor(private formBuilder: FormBuilder) {
          
          
               }
               onHover(i:number){
           this.hoverIndex = i;
          }
               columns = ["name", "Items","status"];
          
          public usersr = [{
              "id": 1,
              "name": "test1"
          
          }, {
              "id": 2,
              "name": "test2",
          
          }];
          
          
            ngOnInit() {
                this.test = false;
                this.groups=[{
                  "id": 1,
                  "name": "pencils",
                  "items": "red pencil",
                  "Status": [{
                      "id": 1,
                      "name": "green"
                  }, {
                      "id": 2,
                      "name": "red"
                  }, {
                      "id": 3,
                      "name": "yellow"
                  }],
                  "loc": [{
                      "id": 1,
                      "name": "loc 1"
                  }, {
                      "id": 2,
                      "name": "loc 2"
                  }, {
                      "id": 3,
                      "name": "loc 3"
                  }]
              },
              {
                  "id": 2,
                  "name": "rubbers",
                  "items": "big rubber",
                  "Status": [{
                      "id": 1,
                      "name": "green"
                  }, {
                      "id": 2,
                      "name": "red"
                  }],
                  "loc": [{
                      "id": 1,
                      "name": "loc 2"
                  }, {
                      "id": 2,
                      "name": "loc 3"
                  }]
              },
              {
                  "id": 3,
                  "name": "rubbers1",
                  "items": "big rubber1",
                  "Status": [{
                      "id": 1,
                      "name": "green"
                  }],
                  "loc": [{
                      "id": 1,
                      "name": "loc 2"
                  }, {
                      "id": 2,
                      "name": "loc 3"
                  }]
              }
          
          ];
          
                this.dotsh = false;
          
                console.log(this.groups.length);
          
          this.usersg_checked = [{
              "id": 1,
              "name": "test1"
          
          }, {
              "id": 2,
              "name": "test2",
          
          }];
          
           this.usersr_selected = {"id":1,"name":"test2"};;
          
          this.selectedGroups = [];
          this.dataGroup = this.formBuilder.group({
                      email: ['', Validators.required]
          });
            }
          
            isChecked(id) {
             console.log(this.usersg_checked);
            return this.usersg_checked.some(item => item.id === id);
          }
           get f() { return this.dataGroup.controls; }
          onCheckChange(event) {
            if (event.target.checked) {
           this.selectedGroups.push(event.target.value);
          } else {
           const index = this.selectedGroups.findIndex(item => item === event.target.value);
           if (index !== -1) {
            this.selectedGroups.splice(index, 1);
          }
          }
          }
          
             getFormData(value){
                this.submitted = true;
          
                  // stop here if form is invalid
                  if (this.dataGroup.invalid) {
                      return;
                  }
                value['groups'] = this.selectedGroups;
                console.log(value);
            }
          
          
          }
          

          css

          .status{
              border: 1px solid;
              border-radius: 4px;
              padding: 0px 10px;
              margin-right: 10px;
          }
          .hover-details{
              position: absolute;
          
          
              border: 1px solid;
              padding: 10px;
              width: 164px;
              text-align: left;
              border-radius: 4px;
          }
          .dots{
              position:relative;
          }
          

          【讨论】:

            【解决方案7】:

            您可以直接将slice() 应用于变量。 StackBlitz Demo

            <li *ngFor="let item of list.slice(0, 10);">
               {{item.text}}
            </li>
            

            【讨论】:

            • 就像名字所暗示的那样,如果您不希望任何剩余的项目显示隐藏占用空间,这很好。
            【解决方案8】:

            除了@Gunter 的回答,您还可以使用 trackBy 来提高性能。 trackBy 接受一个有两个参数的函数:index 和 item。您可以从函数返回对象中的唯一值。它将停止重新渲染 ngFor 中已显示的项目。在您的 html 中添加 trackBy 如下。

            <li *ngFor="let item of list; trackBy: trackByFn;let i=index" class="dropdown-item" (click)="onClick(item)">
              <template [ngIf]="i<11">{{item.text}}</template>
            </li>
            

            并在您的 .ts 文件中编写这样的函数。

            trackByfn(index, item) { 
              return item.uniqueValue;
            }
            

            【讨论】:

            • 一个很好的提及 trackBy 选项的使用 :) 我们应该始终关心性能
            【解决方案9】:

            这很好用:

            <template *ngFor="let item of items; let i=index" >
             <ion-slide *ngIf="i<5" >
              <img [src]="item.ItemPic">
             </ion-slide>
            </template>
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-05-19
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多