Issue
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.
Image
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
<app-dashboard></app-dashboard>
<div *ngIf="hero">
<h2>{{ hero.name | uppercase }} Details</h2>
<div><span>id: </span>{{hero.id}}</div>
<div>
<label>name:
</label>
<div><span>name: </span>{{hero.name}}</div>
</div>
<button (click)="goBack()">go back</button>
<button (click)="save()">save</button>
</div>
hero detail class
export class HeroDetailComponent implements OnInit {
@Input() hero: Hero;
constructor(
private route: ActivatedRoute,
private heroService: HeroService,
private location: Location
) {}
ngOnInit(): void {
this.getHero();
}
getHero(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.heroService.getHero(id)
.subscribe(hero => this.hero = hero);
}
goBack(): void {
this.location.back();
}
save(): void {
this.heroService.updateHero(this.hero)
.subscribe(() => this.goBack());
}
}
The dashboard code
<a *ngFor="let hero of heroes" class="col-1-4" routerLink="/detail/{{hero.id}}">
<div class="module hero">
<h4>{{hero.name}}</h4>
</div>
</a>
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/{{hero.id}}" (click)="reloadRoute()">
<div class="module hero">
<h4>{{hero.name}}</h4>
</div>
</a>
Solution
Instead of using the snapshot, subscribe to the params. This is what mine looks like:
ngOnInit(): void {
this.route.params.subscribe(
params => {
const id = +params['id'];
this.getProduct(id);
}
);
}
Answered By – DeborahK
Answer Checked By – Gilberto Lyons (AngularFixing Admin)