简体   繁体   中英

Routing to multiple components on the same page

Each section of my page is a separate component, which is located one after another while scrolling eg:

<sectionA></sectionA>
<sectionB></sectionB>
<sectionC></sectionC>

All the examples I've seen where creating routings to components on different pages, which where (in easiest words) clearing the container <router-outlet></router-outlet> and filling it with the component assigned to given route.

What about the situation I've described, where all components are located on the same page and visible ?

How to set a proper route when scrolled to given section? The idea I have is to create a directive adding classes if sections are visible or not, and assigning a onscroll listener from the main module checking which section is currently visible and assigning the route respectively. Is this a correct approach?

How to link to a given section? Using regular href=#sectionId or the built in angular link directives?

For this, you can use name-router-outlet as shown here

DEMO: 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM