0

I would navigate between two products, localhost:4200/products/444 to localhost:4200/products/555.

The url changes when I navigate between them but nothing happened to the DOM, I'm still stuck at 444 product and the url is 555.

I'm using Angular 4

pouyada
  • 341
  • 3
  • 15
Roula Halabi
  • 268
  • 1
  • 6
  • 15

2 Answers2

1

It's because Angular reuses the component.

You have to subscribe to the route params to listen for changes and update the view accordingly.

  constructor(
    private route: ActivatedRoute,
  ) { }

  ngOnInit() {
    this.route.params.subscribe(params => {
      // put the logic of your component here
    });
  }
Ploppy
  • 14,810
  • 6
  • 41
  • 58
0

Make your component look like this :

You must have called your function from constructor.

You need to get ID and call the function from ngOnInit.

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

@Component({
  selector: 'app-comp',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  constructor(private route: ActivatedRoute) {
      this.myFunction(this.myID); // Remove this line from constructor     
    }

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.myID = params['id'];
      this.myFunction(this.myID); // Add your function call in ngOnInit
    });
  }
}

To know the difference between constructor and ngOnInit please click here

Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66