<ul>
<li *ngFor="let hero of heroes | slice:0:10;">
{{ hero.name }}
</li>
</ul>
<p *ngIf="heroes.length > 10" (click)="showMore()">show more 10</p>我想在点击时显示更多的英雄名字..还需要显示还剩下多少个英雄的名字。
发布于 2018-04-24 15:01:23
这里的heroes是一个数组。您编写的ngFor语句将显示该数组的所有元素,因为您没有限制显示的元素总数。
如果您将heroes数组用作临时数组,以便仅包含屏幕上显示的元素,则可以将showMore()函数编写为:
showMore(){
this.heroes.push(//put one of the elements you want to add to the array here)
//you can use this line inside a forloop to add as many elements/heroes as you want
}发布于 2018-04-24 15:25:21
Stackblitz:https://stackblitz.com/edit/angular-vfw7tu
我只想补充一句
<ng-container *ngFor="let hero of heroes; let ndx = index">
<li *ngIf="ndx >= 10">{{ hero.name }}</li>
</ng-container>所以你会得到像这样的东西
<ul>
<li *ngFor="let hero of heroes | slice:0:10">
{{ hero.name }}
</li>
<ng-container *ngIf="showMore">
<ng-container *ngFor="let hero of heroes; let ndx = index">
<li *ngIf="ndx >= 10">{{ hero.name }}</li>
</ng-container>
</ng-container>
</ul>
<button (click)="showMore = true">Show more</button>发布于 2018-04-24 16:33:19
您可以使用slice管道来使用变量,因此,如果您的变量名为"page“,并采用以下值: 0,1,2,3,...,heremes.length/10
<ul>
<li *ngFor="let hero of heroes | slice:page*10:(page+1)*10;">
{{ hero.name }}
</li>
</ul>
<p *ngIf="(page+1)*10<heroes.length" (click)="page=page+1">show more 10</p>
//in your component.ts
page:number=0;https://stackoverflow.com/questions/49995080
复制相似问题