How to update the same component with different params in Angular


I’ve done the tour of heroes from angular. It works perfectly.

Now I want to put the dashboard component in the hero detail view. So it shows me the top of heroes, and after that, the hero detail view.

I have a Router link that loads the same component, but with different params. I want to know, what to do so that when I click on any element from the dashboard this one load a different hero.

This is the code of the hero-detail.component.html

<div *ngIf="hero">
<h2>{{ | uppercase }} Details</h2>
        <div><span>id: </span>{{}}</div>
                <div><span>name: </span>{{}}</div>

<button (click)="goBack()">go back</button>
<button (click)="save()">save</button>

hero detail class

export class HeroDetailComponent implements OnInit {
    @Input() hero: Hero;

      private route: ActivatedRoute,

      private heroService: HeroService,

      private location: Location
    ) {}

    ngOnInit(): void {

    getHero(): void {
      const id = +this.route.snapshot.paramMap.get('id');
        .subscribe(hero => this.hero = hero);

    goBack(): void {
    save(): void {
         .subscribe(() => this.goBack());

The dashboard code

<a *ngFor="let hero of heroes" class="col-1-4" routerLink="/detail/{{}}">
    <div class="module hero">

The router is the same as the tutorial.

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'heroes', component: HeroesComponent },
  { path: 'detail/:id', component: HeroDetailComponent }

A bad solution:

After research a little i found the possibility to add the (click)=”reloadRoute()” to the link, but this one refresh all the page.

<a *ngFor="let hero of heroes" class="col-1-4" routerLink="/detail/{{}}"  (click)="reloadRoute()">
    <div class="module hero">



Instead of using the snapshot, subscribe to the params. This is what mine looks like:

ngOnInit(): void {
        params => {
            const id = +params['id'];

Answered By – DeborahK

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.