首页 > 解决方案 > 无法将 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组件中实现了,不是吗?

标签: angularpaginationangular6ngx-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>

这对我有用。希望,这会对大家有所帮助。


推荐阅读