这是组件ts文件
import { MatTableDataSource, MatPaginator } from "@angular/material";
import { FoodService } from "./food.service";
import { Food } from "./food";
@Component({
selector: "app-food",
templateUrl: "./food.component.html",
styleUrls: ["./food.component.scss"],
})
export class FoodComponent implements OnInit {
@ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
food: Food[];
dataSource: MatTableDataSource<Food> = new MatTableDataSource<Food>(
this.food
);
constructor(private foodService: FoodService) {
this.food = [];
}
ngOnInit() {
this.foodService.getFood().subscribe((data) => {
this.food = data as Food[];
this.dataSource.paginator = this.paginator;
});
}
}
还有HTML文件
<div class="container">
<div class="sub-container">
<mat-card class="example-card" *ngFor="let f of food">
<mat-card-header>
<div>
<img
[src]="f.imgUrl | safe"
alt=""
class="example-header-image"
mat-card-avatar
class="example-header-image"
/>
</div>
<mat-card-title class="card-title">{{ f.title }}</mat-card-title>
<mat-card-subtitle class="card-subtitle">{{
f.subtitle
}}</mat-card-subtitle>
</mat-card-header>
<mat-card-content>
<p>{{ f.text }}</p>
</mat-card-content>
<mat-card-actions>
<button mat-button>LIKE</button>
<button mat-button>SHARE</button>
</mat-card-actions>
</mat-card>
</div>
<mat-paginator
[pageSize]="5"
[pageSizeOptions]="[8, 16, 24, 32]"
></mat-paginator>
</div>
Paginator不起作用,它会上传所有卡。 这是服务器端分页器alla数据取自api; 我不明白为什么它没有分页器检测到数据并将其转换为分页器... 任何想法???
答案 0 :(得分:0)
从响应中检索数据后,尝试声明MatTableDataSource。
import { MatTableDataSource, MatPaginator } from "@angular/material";
import { FoodService } from "./food.service";
import { Food } from "./food";
@Component({
selector: "app-food",
templateUrl: "./food.component.html",
styleUrls: ["./food.component.scss"],
})
export class FoodComponent implements OnInit {
@ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
food: Food[];
dataSource: MatTableDataSource<Food> = new MatTableDataSource<Food>(
this.food
);
constructor(private foodService: FoodService) {
this.food = [];
}
ngOnInit() {
this.foodService.getFood().subscribe((data) => {
this.food = data as Food[];
this.dataSource = new MatTableDataSource<Food>(this.food);
this.dataSource.paginator = this.paginator;
});
}
}