chink
chink

Reputation: 1643

Routing to same component with different routing is not working in Angular

I have an angular project in which I have a navbar to route to different components. Two of the navigations in the navbar navigate to the same component but with different parameters. When I try to navigate to any of these two navigations from navbar it works fine.

But if I try to navigate from one of these navigations to other navigation with the same route and different parameter, it is not working.

My ngOnit function

ngOnInit(): void {
        this.configId = this.route.snapshot.paramMap.get('id')
        this.getConfigurations();
    }

Looking at an answer from a similar question I changed my code to

    ngOnInit(): void {
        this.sub = this.route.params.subscribe(params => {
            this.configId = params['id']
        })
        this.getConfigurations();
    }

    ngOnDestroy(): void{
        this.sub.unsubscribe()
    }

But still I see the same behaviour.

Edit

Route configuration

{ path: 'admin/program/:id', component: ConfigurationView , canActivate: [AuthGuard], data: {
        breadcrumb: [
            {
              label: 'Admin',
              url: ''
            },
            {
                label: 'Program ',
                url: ''
            }
          ]
        }
    },

Upvotes: 1

Views: 1275

Answers (1)

andsilver
andsilver

Reputation: 5972

ngOnInit is only called when a component is inserted to the DOM Tree.

When you navigate in the same path with just different id, Angular doesn't re-render the component.(so ngOnInit is not called again and you cannot get id inside the ngOnInit)

Instead, you should watch your params change like what you did, but you need to move your getConfiguration() inside the subscription callback.

this.sub = this.route.params.subscribe(params => {
  this.configId = params['id']
  this.getConfigurations();
})

Upvotes: 4

Related Questions