使用 angular-router 在页面中导航视图

Using angular-router to navigate views within a page

我正在创建一个包含多个页面的 Web 应用程序,每个页面中都有动态部分。我希望每个部分都使用 angular 路由器。

我试过简单地在组件中放置一个命名的路由器插座,但它似乎不起作用...有什么想法吗?

这是我的一般设置。

应用模板

<main>
  <router-outlet></router-outlet>
</main>

应用模块

const routes: Routes = [
 { 
  path: 'page', 
  component: PageModule
 }
];

@NgModule({
  imports: [PageModule, RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

页面模板:

<tabset>
  <tab>
    <router-outlet name="section1"></router-outlet>
  </tab>
  <tab>
    <router-outlet name="section2"></router-outlet>
  </tab>
</tabset>

页面模块

const routes: Routes = [
  {
    path: '',
    component: PageComponent,
  },
  {
    path: 'section1-view1',
    component: View1Component,
    outlet: 'section1',
  },
  {
    path: 'section1-view2',
    component: View2Component,
    outlet: 'section1',
  }
  // More routes ...
];

@NgModule({
  declarations: [
    PageComponent,
    View1Component,
    View2Component
  ],
  imports: [
    RouterModule.forChild(routes),
    CommonModule,
    TabsetModule
  ]
})
export class PageModule { constructor(){} }

已更新

试试这个

创建两个单独的组件显示在主页上

ng g c section1
ng g c section2

section1 .ts 文件

@Component({
  selector: 'section1',
  templateUrl: './section1.component.html',
  styleUrls: ['./section1.component.css'],
})

类似section2 .ts文件

@Component({
      selector: 'section2',
      templateUrl: './section2.component.html',
      styleUrls: ['./section2.component.css'],
    })

然后在主页上你可以像这样使用多个sections/components

页面模板

<div class="row">
  <div class="col-sm-5">
    <section1></section1> <!-- component selector -->
  </div>
  <div class="col-sm-5">
    <section2></section2>
  </div>
</div>

在新模块中创建每个组件,然后在该模块中定义内部路由,这样无论何时路由到该模块,都可以在内部路由中路由。

保持当前路由不变,并声明新模块(在 app.module 中导入这些模块),并在该模块内创建您要在该模块中路由的新组件。

检查一下:Stackblitz 只是供您使用的示例。

app.module 中有一个组件,intmodule 中有一个组件,intmodule 中有两个组件。 从 app.module 我们可以在 hello.componentintmodule 之间路由,在 intmodule 我们可以在 comp1 和 comp2 之间路由。

评论以获得更多帮助:)