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

送分小仙女□ 提交于 2019-12-06 06:08:52

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;

  constructor(private route: ActivatedRoute) {}

  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

If understand correctly the question, I think you should simply put the Section1Counter component in the AppWrapper component template and remove it from SectionxPagey components. In this way you woul use the router-outlet to display the pages while the Section1Counter would remain the same instance. I hope this helps

There is a module ng2-cache which will allow you to cache a component into local storage and also provide rules for the caching. I think it should do what you are looking for.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!