在这里您可以找到一个示例应用程序:http://ivan-khludov.com/
这是我的根组件:
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 {
}
第 1 部分第 1 页的组件:
import { Component } from '@angular/core';
@Component({
selector: 'secapagea',
template: `
<h2>Section 1 - Page 1</h2>
<countera></countera>
`
})
export class Section1Page1 {
}
第 1 节第 2 页几乎相同:
import { Component } from '@angular/core';
@Component({
selector: 'secapageb',
template: `
<h2>Section 1 - Page 2</h2>
<countera></countera>
`
})
export class Section1Page2 {
}
计数器组件:
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);
}
}
以我打开该部分第一页的情况为例。有没有办法在不重新加载计数器的情况下导航到同一部分的第二页?我想为此类导航问题找到一个通用的解决方案——它可以不是计数器组件,而是侧边栏导航或部分标题或其他东西。
最佳答案
是的,绝对可以编写一个可以处理多个路由的组件,而无需每次都重建组件。
如果您创建一个组件来处理所有页面,如以下路由所定义:
const routes: Routes = [
{ path: 'section-1/:page', component: Section1PageX }
];
您可以订阅路由参数“page”并在您的组件中处理页面更改。这可以防止 Angular2 每次都重建页面组件。
@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();
}
}
因此,只有当您离开整个部分时,您的 Section1Counter 组件才会被销毁。
您还可以在我们的博客文章 Angular 2 by Example 中阅读更多相关信息
关于javascript - Angular 2——在不重新加载这些页面通用的组件的情况下浏览网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40438164/