Lzhelenin Lzhelenin - 1 month ago 11
AngularJS Question

Angular 2 — navigate through web pages without reloading a component that is common for those pages

Here you can find an example app: http://ivan-khludov.com/

This is my root component:

import { Component } from '@angular/core';

@Component({
selector: 'root',
template: `
<h1>My Dummy Angular App</h1>
<router-outlet></router-outlet>
<nav>
<a routerLink="/section-1/1" routerLinkActive="active">Section 1 - Page 1</a>
<span>||</span>
<a routerLink="/section-1/2" routerLinkActive="active">Section 1 - Page 2</a>
<span>||</span>
<a routerLink="/section-2/1" routerLinkActive="active">Section 2 - Page 1</a>
<span>||</span>
<a routerLink="/section-2/2" routerLinkActive="active">Section 2 - Page 2</a>
</nav>
`
})

export class AppWrapper {

}


A component for section 1, page 1:

import { Component } from '@angular/core';

@Component({
selector: 'secapagea',
template: `
<h2>Section 1 - Page 1</h2>
<countera></countera>
`
})

export class Section1Page1 {

}


Almost the same thing for section 1, page 2:

import { Component } from '@angular/core';

@Component({
selector: 'secapageb',
template: `
<h2>Section 1 - Page 2</h2>
<countera></countera>
`
})

export class Section1Page2 {

}


A counter component:

import { Component } from '@angular/core';

@Component({
selector: 'countera',
template: `
<div>Seconds elapsed: {{this.count}}</div>
`
})

export class Section1Counter {

count: number;

constructor() {

this.count = 0;

setInterval(() => {

this.count ++;

}, 1000);

}

}


Put the case that I opened the first page of the section. Is there a way to navigate to the second page of the same section without reloading the counter? I want to find a general solution for such navigation issues — it could be not a counter component but sidebar navigation or section heading or something else.

Answer

Yeah it is absolutely possible to write a Component which can handle multiple Routes without reconstructing the Component each time.

If you create a component which handles all pages together as defined with the following route:

const routes: Routes = [
  { path: 'section-1/:page', component: Section1PageX }
];

You can subscribe on the route parameter "page" and handle the page change within your Component. This prevents Angular2 from reconstructing the page Component each time.

@Component({
  selector: 'secapagea',
  template: `
  <h2>Section 1 - Page {{page}}</h2>
  <countera></countera>
  `
})
export Section1PageX {
  private page: string;

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.page = params['page'];
       //handle the page change
    });  
  }

  ngOnDestroy() {
    //unsubscribe when you leave the section
    this.sub.unsubscribe();
  }
}

So your Section1Counter Component will only be destroyed if you leave the entire section.

You can also read more about this in our Blog Post Angular 2 by Example