我希望在角度中使用for循环,因为我想在页面系统的ngFor循环中显示有限数量的数据。我的意思是我想显示1到20个数据。然后我点击“下一步”按钮转到下一页,所以我应该显示21到40之间的数据等...
即使在我阅读文档后,我也不明白如何使用ngFor循环(https://angular.io/api/common/NgForOf)
我希望在角度中使用for循环,因为我想在页面系统的ngFor循环中显示有限数量的数据。我的意思是我想显示1到20个数据。然后我点击“下一步”按钮转到下一页,所以我应该显示21到40之间的数据等...
如果是这样检查WORKING STACKBLITZ 📄📄
你的component.html
看起来像这样
<div class="container">
<pager [itemCount]="100" [(pageIndex)]="pageIndex" [pageSize]="pageSize"></pager>
<table class="table table-sm">
<thead>
<tr>
<th *ngFor="let fieldName of fieldNames">{{fieldName}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of items | slice:pageIndex*pageSize:(pageIndex+1)*pageSize">
<td *ngFor="let name of fieldNames">{{item[name]}}</td>
</tr>
</tbody>
</table>
</div>
而你的component.ts
可能看起来像这样
export class AppComponent {
items: object[];
fieldNames: string[];
pageIndex: number;
pageSize: number;
constructor(appService: AppService) {
this.items = appService.getOrders(100);
this.fieldNames = [ 'No', 'Name', 'Date', 'Amount' ];
this.pageIndex = 0;
this.pageSize = 10;
}
}
希望这有用!
如果我理解正确!
您可以使用两个变量,这两个变量将用作偏移(起始点)和限制(结束点):
HTML代码:
<div class="example-container">
<mat-form-field>
<input matInput placeholder="Input" [(ngModel)]="limit">
</mat-form-field>
<button mat-raised-button color="primary" (click)="generateNumbers()">Generate page list</button>
<div *ngFor="let page of pageList">
{{page}}
</div>
</div>
TS代码:
import { Component } from '@angular/core';
/** @title Simple form field */
@Component({
selector: 'form-field-overview-example',
templateUrl: 'form-field-overview-example.html',
styleUrls: ['form-field-overview-example.css'],
})
export class FormFieldOverviewExample {
offset: any = 1;
limit: any = 20;
pageList: any[] = [];
generateNumbers() {
this.pageList = [];
for (var i = 1; i <= this.limit; i++) {
this.pageList.push(i);
}
}
}
您可以将新数据绑定到View。绑定数据初始化为源数据的1-20。单击时,next button
将数据更改为21-40。