如何使用* ngFor迭代前几个元素

时间:2018-06-18 11:29:33

标签: angular ngfor

我正在尝试开发一个角度(版本6)应用程序,并使用* ngFor inn来迭代一个数组。在HTML中我只想查看前8个元素,因为输出设计变得不均匀。其余的元素可以存储为下一个按钮调用。 我知道一种方法是限制我在其上调用* ngFor的数组为8,但这看起来更像是一个黑客而不是其他任何东西。任何帮助将非常感激。提前致谢。 HTML ----->

<div *ngIf="!isloading" style = "padding-right: 300px; padding-left: 300px">
    <ng-container *ngIf="cards">
    <div *ngFor ="let card of cards">
    <app-card [card]="card" ></app-card>
    </div>
</ng-container>
</div>
<div class ="loader" *ngIf = "isloading">

JS ---&GT;

@Component({
  selector: 'app-feed',
  templateUrl: './feed.component.html',
  styleUrls: ['./feed.component.css']
})
export class FeedComponent implements OnInit {
  @Input() cat :string; 
  @Input() sucat:string;



  //These 4 to represent current feed cat and supercat
  private curcat : string;
  private cursu : string;
  private page : number;
  //to  determine if page loading 
  private isloading : boolean = false;


  //These to  deal with the the JSON of the response Data
  private cards : Card[] = [];
  private itemcount : number;
  private lastpage : number  = 10;
  constructor(private contentservice: ContentService) { }

  ngOnChanges(changes : SimpleChange){
    this.currentfeedparam(this.cat,this.sucat);
    this.fetchdata(this.cursu,this.curcat);
  }

  ngOnInit(){
  }

  currentfeedparam(c:string,s:string){
    //this fucntion to set feed status
    this.curcat = c;
    this.cursu = s;
    this.page = 1;  
  }

  fetchdata(su :string,cat : string){
  this.isloading = true;  
  if(this.lastpage >=  this.page){
    this.contentservice.getcontentdata(cat,su,this.page)
    .subscribe((response) => {
      this.isloading = false;  
      const data = new JsonData(response);
      this.lastpage = data.lastPage;
      console.log(this.page+' '+this.lastpage);
      this.page++;//
      this.cards = data.items;
      });

  }
  else{
    console.log('last page reached');
    this.isloading = false;  
  }
}

}

2 个答案:

答案 0 :(得分:5)

您可以尝试此解决方案

您可以使用slice管道。

<div *ngIf="!isloading" style = "padding-right: 300px; padding-left: 300px">
    <ng-container *ngIf="cards">
    <div *ngFor ="let card of cards | slice:0:8;">
    <app-card [card]="card" ></app-card>
    </div>
</ng-container>
</div>
<div class ="loader" *ngIf = "isloading">

答案 1 :(得分:2)

方法1:

  1. 创建一个新数组并将要显示的项目放在那里,例如

    this.filteredCards = this.cards.slice(startIndex, 8);
    
  2. 并在你的循环中使用它,当你想要显示其他牌时更改startIndex:

    <div *ngFor ="let card of filteredCards">
        <app-card [card]="card" ></app-card>
    </div>
    

    方法2

    <ng-container *ngFor ="let card of cards; let i=index">
      <div *ngIf="i <= 8">
        <app-card [card]="card" ></app-card>
      </ng-container>
    </div>