Lin Li
Lin Li

Reputation: 21

In Angular2 routing, the URL changed but the content doesn't update

I am a beginner of Angular2. When I am learning angular2 routing service from https://angular.io/tutorial/toh-pt5. I want to have herocomponent always displayed so I in the app.component.html like this:

<h1>{{title}}</h1>
<nav>
  <a routerLink="/dashboard">Dashboard</a>
  <a routerLink="/heroes">Heroes</a>
  <a routerLink="/dummy">Dummy</a>
</nav>
<app-heroes></app-heroes>
<router-outlet></router-outlet>
<app-messages></app-messages>

And here is the app-routing.module.ts:

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { DashboardComponent }   from './dashboard/dashboard.component';
import { HeroesComponent }      from './heroes/heroes.component';
import { HeroDetailComponent }  from './hero-detail/hero-detail.component';
import {DummyComponentComponent} from './dummy-component/dummy-component.component';
const routes: Routes = [
  { path: '', redirectTo: '/', pathMatch: 'full' },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'detail/:id', component: HeroDetailComponent },
  { path: 'heroes', component: HeroesComponent },
  {path: 'dummy',component:DummyComponentComponent}
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

Strangely, when I click a hero on /dashboard or /heroes page it can direct to the correct URL and show the correct hero detail.

However, when I am on /detail/{{hero.id}} and click the hero on the hero component it can redirect the URL but the content in doesn't update. Can someone please help me with this?

Upvotes: 2

Views: 4886

Answers (2)

Pranay Rana
Pranay Rana

Reputation: 176896

if below is not issue then it should be issue that you are just changing parameter url that is reason its not updating

//put this code in your hero.component.ts file 
ngOnInit() {
this.route.params.subscribe((params) => {
   this.id = +params['id'];
   this.loadComponentAgain();
 });
}

above code monitor change in param value and update your component according to it.


There is issue because of this html

<app-heroes></app-heroes>
<router-outlet></router-outlet>

you are loading app-heroes component out side router-outlet, it should be loaded under router-outlet, so you should do this

<!-- <app-heroes></app-heroes> remove this-->
<router-outlet></router-outlet>

Upvotes: 2

Jaya Krishna
Jaya Krishna

Reputation: 313

For changing a route with dynamic value you need to set your routerLink like this

[routerLink]="['/detail',hero.id]"

Upvotes: 1

Related Questions