我的页面的每个部分都是一个单独的组件,在滚动时依次定位,例如:
<sectionA></sectionA>
<sectionB></sectionB>
<sectionC></sectionC>
我见过的所有示例都在不同页面上创建到组件的路由,其中(用最简单的话来说)清除容器 <router-outlet></router-outlet>
并用分配给给定路由的组件填充它。
我描述的所有组件都位于同一页面并且可见的情况怎么样?
滚动到给定部分时如何设置正确的路线?我的想法是创建一个指令,如果部分可见或不可见,则添加类,并从主模块分配一个 onscroll 监听器,检查哪个部分当前可见并分别分配路线。这是正确的做法吗?
如何链接到给定部分?使用常规href=#sectionId
或者内置的 Angular 链接指令?
最佳答案
为此,您可以使用name-router-outlet,如下所示
演示:https://plnkr.co/edit/91YUcXI1la3B9dxzXSJp?p=preview
App.Component.ts
@Component({
selector:"my-app",
template:`
<h3>Normal router-outlet</h3>
<router-outlet></router-outlet>
<hr>
<h3>sectionA : named-router-outlet</h3>
<router-outlet name='sectionA'></router-outlet>
<hr>
<h3>SectionB : named-router-outlet</h3>
<router-outlet name='sectionB'></router-outlet>
`
})
app.routing.ts
import { Routes,RouterModule } from '@angular/router';
import {HomeComponent} from './home.component';
import {SectionA} from './sectionA';
import {SectionB} from './sectionB';
let routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full'},
{ path: 'home', component: HomeComponent},
{ path: '', outlet: 'sectionA', component: SectionA},
{ path: '', outlet: 'sectionB', component: SectionB}
];
export const routing = RouterModule.forRoot(routes);
关于javascript - 路由到同一页面上的多个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39878475/