Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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>

Github

like image 637
ValRob Avatar asked Oct 23 '25 22:10

ValRob


1 Answers

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);
        }
    );
}
like image 89
DeborahK Avatar answered Oct 25 '25 16:10

DeborahK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!