1

I'm new in Angular and I have problem with pass params from url to view on first load.

In my URL i have parameter page:

.../catalog?page=3

In component I have next code:

export class CatalogListComponent implements OnInit {
     page;

     constructor(private route: ActivatedRoute){
     }

     ngOnInit(){
       this.route.queryParams.subscribe(params => {
          this.page = +params['page'] || 1;
        });
     }

     setPage(page: number) {
    this.router.navigate(['catalog'], { queryParams: {...this.queryParams, page } });
  }
}

In view I use ngb-pagination:

<ngb-pagination class="pagination"
                              [collectionSize]="items.total"
                              [rotate]="true"
                              [(page)]="page"
                              [maxSize]="5"
                              [pageSize]="20"
                              (pageChange)="setPage(page)"
              >
</ngb-pagination>

When I'm open/refresh link in browser .../catalog?page=3 ngb-pagination always shows me page 1 instead of 3, but next navigation works fine([page num in url and in pagination the same).

What I'm doing wrong ?

Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83
Alex K
  • 2,613
  • 1
  • 20
  • 31

3 Answers3

0

As answered before, you should refactor your method with the following code:

 ngOnInit(){
       this.route.queryParams.subscribe(params => {
          this.page = params['page'];
        });
     }

And there is a little trick to print what you want in the console:

console.log('my value is: ', example);
Alberto AM
  • 310
  • 2
  • 12
0
<ngb-pagination [collectionSize]="total | async" 
(pageChange)="pageChanged($event)"  
[(page)]="page" aria-label="Pagination"></ngb-pagination>

you should use / pass the $event as argument instead of page

Ref : http://plnkr.co/edit/TDm5rv4RmxIKoWYWp8Qa?p=preview

Senthil
  • 2,156
  • 1
  • 14
  • 19
  • Seems to be duplicate . Rer here https://stackoverflow.com/questions/41223400/how-to-implement-bootstrap-4-for-angular-2-ngb-pagination – Senthil Nov 28 '18 at 14:25
0

You should add *ngIf directive as attribute to ngb-pagination. The code should look like this

<ngb-pagination *ngIf="total" [collectionSize]="total"...></ngb-pagination>

It worked in my case.

Przemek
  • 647
  • 2
  • 8
  • 25