1

I have List and Details components in an Angular (v7) project and I open the Details of a record using the following approach:

ListComponent.html:

<a routerLink="/details/" [state]="{ id: row.Id }">{{ row.Title }}</a>


DetailsComponent.ts:

import { Router, ActivatedRoute } from '@angular/router';

export class DetailsComponent {

    constructor(private router: Router,
        public activatedRoute: ActivatedRoute {
        super();

        this.id = this.router.getCurrentNavigation().extras.state.id; //get id parameter
    }
}

I have encountered 2 issues to be fixed:

1) I need to stay on the same Details page on page refresh.

2) I want to open Details page for a record using a button click e.g. appending id parameter to the address of the Details page.

Is it possible to fix these 2 issues in a smart way in Angular 7?

Jack
  • 1
  • 21
  • 118
  • 236

1 Answers1

2

You should add the id as a router parameter in the url. And make a new route in your routing-module that corresponds with the detail component.

You can see this here in the official documentation where they implement a list/detail view with routing.

Basically it would be like this

<a routerLink="/details/{{row.Id}}">{{ row.Title }}</a>

and

import { Router, ActivatedRoute } from '@angular/router';

export class DetailsComponent {

    constructor(private router: Router,
        public route: ActivatedRoute) {
        super();

        this.id = this.route.snapshot.paramMap.get('id'); //get id parameter
    }
}
Korfoo
  • 571
  • 2
  • 12
  • Thanks for reply. First of all I use the button in email message and I think I should use href instead of routerLink. On the other hand there is an error on the id line because there is no snapshot property in this.route or this.router. Any idea? – Jack Jun 11 '19 at 13:17
  • I don't understand what you mean with the email message. For the snpashot property, I made a mistake in the injection. I changed ` public activatedroute: ActivatedRoute` to ` public route: ActivatedRoute`. The `snapshot` property is a member of `ActivatedRoute`. – Korfoo Jun 11 '19 at 14:08
  • Thşis approach seem to work, BUT when refreshing Details page, **HTTP Error 404.0 - Not Found** error encountered even if the address is the same as when opening Details page first (.../detail/216). Any idea? – Jack Jun 12 '19 at 07:37
  • You are probably using the new `PathLocationStrategy` but haven't configured your webserver to handle this correctly. You can read more about that [here](https://angular.io/guide/router#appendix-locationstrategy-and-browser-url-styles) – Korfoo Jun 12 '19 at 10:26
  • Thanks for your helps, voted up. I solved the problem and post the fix on **[Cannot navigate same route in Angular](https://stackoverflow.com/questions/56559158/cannot-navigate-same-route-in-angular/56563350#56563350)**. Regards... – Jack Jun 12 '19 at 13:26