Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngOnInit not called when same component is loaded with different data

I have an angular 2 app, and I use router to navigate between views, like everyone else. Here is how my path for a particular component look 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 SectionEditComponent for section1 and section2.

Path1: pane/1/section/1
Path2: pane/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 same ViewComponent, the ngOnInit() is not called, thus not loading the new path, even though the url actually change according to the new section ID.

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

like image 957
Sanjay Verma Avatar asked Oct 10 '16 16:10

Sanjay Verma


2 Answers

Inject the route and subscribe to parameters change

constructor(route:ActivatedRoute) {
  route.params.forEach(params => {
    myInit(params['paramId']);
  });
}
like image 153
Günter Zöchbauer Avatar answered Oct 17 '22 03:10

Günter Zöchbauer


I had a similar issue with ngOnInit not being called on route change. I moved the code to ngAfterViewInit() and it worked.

like image 37
Manoj Amalraj Avatar answered Oct 17 '22 03:10

Manoj Amalraj