Search code examples
angularangular-router

Angular: detail view returns to list with pagination


I have an angular application using version 4.

It has a component with a mat-table and pagination mat-paginator.

Each row has router navigation to details.

The problem:

When the user change to page 2, then navigates to details and then returns, the component shows information with page 1, instead of page 2.

How can the application return to page 2 ??

Thanks!


Solution

  • When the user navigates away from a component, that component and its template are destroyed. Angular remembers nothing about the component. So when the user navigates back, the component initializes itself as if it has never been shown before.

    If you need a component to remember its settings (such as which page it was on) you need to set this up somewhere. You can build a service that holds the values. The component can then set the page that the user is on. When the component is initialized again, it can read its last state from the service.

    I have an example of a service that does this here: https://github.com/DeborahK/MovieHunter-routing/blob/master/src/app/movies/movie-parameter.service.ts

    In this example, the service remembers the last entered filter criteria. But you could do something similar for it to remember its last page.

    Alternatively, you can pass state information on the route using query parameters. Then pass that state information to the detail component and back to the table component when the user navigates back.

    The first option (using a service) is probably a better choice.