angular - 无法将 ngModel 绑定到 ngx-bootstrap 分页
问题描述
我正在构建一个组件。这是一个带有分页的简单列表,可以从 Web 服务中获取数据。我正在使用引导程序列出值和ngx-bootstrap 分页组件。
问题是currentPage属性不能正常工作。该值已附加到变量,但组件显示错误信息。
在组件内部,变量具有 @Input 装饰器
@Input() listFields?: string[]; //list of displayable fields in the list
@Input() resourceService: ResourceService<T>; //webservice to fetch data
@Input() pageSize ?: number; //number of items to receive from the webservice
@Input() currentPage ?: number = 1; //current page
@Input() modelParams?: HttpParams; //other parameters to send to the webservice
上述变量从 ngx-bootstrap 发送到分页组件。
<pagination [(itemsPerPage)]="pageSize" [(ngModel)]="currentPage" [(totalItems)]="page.totalCount"
(pageChanged)="pageChanged($event)"></pagination>
我正在开发的组件接收来自@inputs 的值,如下所述。
<general-resource-list
[resourceService]="workshopService"
[listFields]="listFieldsWorkshop"
[currentPage]="currentPage"
[pageSize]="pageSize"
[modelParams]="pageParams">
</general-resource-list>
@Component({
selector: 'app-workshops-list',
templateUrl: './workshops-list.component.html',
styleUrls: ['./workshops-list.component.scss']
})
export class WorkshopsListComponent{
public listFieldsWorkshop = ['id','name','version'];
public title = "Workshop List";
public currentPage:number;
public pageSize:number;
public pageParams:HttpParams;
constructor(
public workshopService: WorkshopService,
public workShopRoute: ActivatedRoute,
public workshopRouter: Router) {
this.workShopRoute.queryParams.subscribe(params => {
this.pageParams = new HttpParams();
for(let key in params){
if(!["page","pageSize"].includes(key)){
this.pageParams = this.pageParams.append(key,params[key]);
}
}
this.currentPage = params['page']? params['page']:1;
this.pageSize = params['pageSize']? params['pageSize']:10;
});
}
}
首先,我认为这是因为 @Input 是在渲染组件之后加载的,但是即使我在构造函数中或直接在变量声明中设置值,它也不起作用。
PS:pageSize 属性是有效的,它的使用和 currentPage 一样。
PS2:我不认为是实现ControlValueAccessor的情况,这应该已经在ngx-bootstrap组件中实现了,不是吗?
解决方案
出现这个问题是因为currentPage的值被重置为 1。原因是在获取数据之前(最初)totalItems(这里 page.totalCount)为 0,因此currentPage被重置为 1。作为一个简单的方法,您可以添加一个*ngIf。
IE,
<div *ngIf="page.totalCount">
<pagination [(itemsPerPage)]="pageSize" [(ngModel)]="currentPage" [(totalItems)]="page.totalCount"
(pageChanged)="pageChanged($event)"></pagination>
</div>
这对我有用。希望,这会对大家有所帮助。
推荐阅读
- java - 如何反序列化 Android Notification 的附加功能中的 Parceled “android.messages”?
- ruby-on-rails - 如何在 Rails 中设置没有特定父 ID 的子索引路径?
- php - 尝试登录时,Wordpress 重定向到本地 IP 地址
- python - 如何在与点相交的图像上绘制网格?
- c# - 向 CP290 打印机发送命令时出现问题?
- python - 填补 pandas df 的空白
- mysql - Laravel 一对多(反向)/属于返回 null
- c++ - C++ 向量 push_back 没有复制?
- redis - 检查管道中的 BRPOPLPUSH 是否超时
- ios - “..将此密码保存在您的钥匙串中..”和“...将此密码保存在您的 icloud 钥匙串中”消息同时显示