NgOnInit is not called when the same component loads with different data

I have an angular 2 application, and I use a router to navigate between views, like everyone else. Here's what my path to a specific component looks like:

{ path: 'home/view1/:viewID', component: ViewComponent, children: [ { path: 'pane/:paneId/section/:sectionId', component: SectionEditComponent }, { path: '**', component: ViewEditComponent } ] }, 

Now I have two buttons on the ViewComponent to load the EditComponent section for section1 and section2.

Path 1: panel / 1 / section / 1
Path2: Panel / 1 / Section / 2

ViewComponent Template:

  <div class="col-md-8" style="background-color: white; height: 100%"> <button (click)="loadPath(1)">Path1</button> <button (click)="loadPath(2)">Path2</button> <router-outlet></router-outlet> </div> 

Now when I navigate from Path1-> Path2 or Path2-> Path1 within the same ViewComponent, ngOnInit () is not called, so it doesn’t load the new path, even if the URL does change to match the new section identifier.

Is this known or expected behavior? Is there something I'm doing wrong?

+7
angular angular2-routing
source share
4 answers

Enter a route and subscribe to change settings

 constructor(route:ActivatedRoute) { route.params.forEach(params => { myInit(params['paramId']); }); } 
+6
source share

I just wanted to add that if you use a route resolver to get data before loading components, you can put the following code in your ngOnInit component:

 ngOnInit(){ this.activatedRoute.data.subscribe(data => { initData(data['mydata']); }); } initData(data){ // process new data } 

Now, when your recognizer updates the data on allowed routes, your component model will be updated and display new data.

+6
source share

For the same component instance, ngOnInit() is called only once.

+3
source share

I had a similar problem since ngOnInit was not called when changing the route. I moved the code to ngAfterViewInit () and it worked.

+1
source share

All Articles