【问题标题】:How to display a component at the start of a application while it is still a child component?如何在应用程序开始时显示组件,而它仍然是子组件?
【发布时间】:2020-07-29 10:31:57
【问题描述】:

我创建了一个项目来说明我的问题:

我有一个父组件,其中两个子组件应该可以通过链接访问

<p>Child1 should be displayed by default at the start of the app</p>
<!-- <app-child1> </app-child1> --> 
<a [routerLink]="['/child1']" routerLinkActive="router-link-active">Child1</a>
<a [routerLink]="['/child2']"> Child 2</a> 

<router-outlet></router-outlet>

问题是,在应用程序的开始处,默认情况下应该显示 child1 组件,但是单击指向 child2 的链接时,child one 的内容应该消失了。所以当时应该只加载一个孩子(路由器插座)。

我的路由模块

const routes: Routes = [
  {path: '', component: ParentComponent, children: [
    {path: 'child1', component: Child1Component},
    {path: 'child2', component: Child2Component}
  ]}
];

如何使用 Angular 路由解决这个问题,还是必须设置一些布尔值并使用 *ngIf?

【问题讨论】:

  • 检查 Routes 数组的重定向属性。
  • 感谢您的评论!我去查一下!
  • 不需要 ngIf,请创建一个 stackblitz 复制品,以便我提供帮助。
  • 我现在就创建一个!

标签: angular typescript parent-child angular-routing


【解决方案1】:

添加默认子路由组件重定向:

const routes: Routes = [
  { path: '', component: ParentComponent, children: [
    { path: 'child1', component: Child1Component },
    { path: 'child2', component: Child2Component },
    { path: '',   redirectTo: '/child1', pathMatch: 'full' },
  ]}
];

并将另一个&lt;router-outlet&gt;&lt;/router-outlet&gt; 添加到您的父组件。我创建了一个STACKBLITZ 来说明它。所有组件都在同一个 ts 文件中,只是为了简单。

您可以在official site 阅读更多内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-02
    • 1970-01-01
    • 2022-01-21
    • 2015-01-03
    • 2020-02-22
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    相关资源
    最近更新 更多