【问题标题】:Using angular-router to navigate views within a page使用 angular-router 在页面中导航视图
【发布时间】:2019-11-11 08:55:19
【问题描述】:

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

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

这是我的一般设置。

应用模板

<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(){} }

【问题讨论】:

  • 您是在寻找路线来确定要显示哪个选项卡或确定每个选项卡上显示什么?
  • 要在路由页面中路由吗?
  • 不清楚您要完成什么。你的意思是每个部分都应该有一个url链接?像在角度文档页面中一样? (喜欢这个链接:angular.io/guide/ngmodules#angular-modularity
  • @KautilyaKatiha,是的!我想在路由页面内路由。 :)
  • 我希望每个选项卡的内容由路由控制,并且我希望这些选项卡位于也通过路由器包含的页面上。

标签: javascript angular angular7 angular-routing angular7-router


【解决方案1】:

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

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

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

这里app.module 中有一个组件和一个名为intmodule 的模块,intmodule 中有两个组件。 从app.module 我们可以在hello.componentintmodule 之间进行路由,在intmodule 中我们可以在comp1 和comp2 之间进行路由。

评论以获得更多帮助:)

【讨论】:

  • 我相信这是我正在做的事情,但它不起作用。你能举个例子吗?
  • 检查我添加的 stackblitz。希望这会有所帮助。
【解决方案2】:

更新

试试这个

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

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'],
    })

然后在主页上,您可以像这样使用多个部分/组件

页面模板

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

【讨论】:

  • 是的,我知道这可以工作,但动态组件需要后退按钮功能并且需要更改 URL。我可以编写自己的路由器,但我希望使用内置的路由器功能。
猜你喜欢
  • 2020-07-09
  • 2016-11-27
  • 2019-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
相关资源
最近更新 更多