如何在应用程序启动时显示组件,而它仍然是 child 组件?
How to display a component at the start of a application while it is still a child component?
我创建了一个项目来说明我的问题:
我有一个 parent 组件,其中两个 child 组件应该可以通过 link
访问
<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 组件应该默认显示,但单击 link 到 child2 [=26] 的内容=] 一个应该消失了。所以当时应该只加载 child 之一 (router-outlet)。
我的routing-module
const routes: Routes = [
{path: '', component: ParentComponent, children: [
{path: 'child1', component: Child1Component},
{path: 'child2', component: Child2Component}
]}
];
如何使用 Angular 路由解决这个问题,或者我是否必须设置一些布尔值并使用 *ngIf?
添加默认子路由组件重定向:
const routes: Routes = [
{ path: '', component: ParentComponent, children: [
{ path: 'child1', component: Child1Component },
{ path: 'child2', component: Child2Component },
{ path: '', redirectTo: '/child1', pathMatch: 'full' },
]}
];
并向您的父组件添加另一个 <router-outlet></router-outlet>
。我创建了一个 STACKBLITZ 来说明它。为了简单起见,所有组件都在同一个 ts 文件中。
您可以在 official site 阅读更多内容。
我创建了一个项目来说明我的问题:
我有一个 parent 组件,其中两个 child 组件应该可以通过 link
访问<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 组件应该默认显示,但单击 link 到 child2 [=26] 的内容=] 一个应该消失了。所以当时应该只加载 child 之一 (router-outlet)。
我的routing-module
const routes: Routes = [
{path: '', component: ParentComponent, children: [
{path: 'child1', component: Child1Component},
{path: 'child2', component: Child2Component}
]}
];
如何使用 Angular 路由解决这个问题,或者我是否必须设置一些布尔值并使用 *ngIf?
添加默认子路由组件重定向:
const routes: Routes = [
{ path: '', component: ParentComponent, children: [
{ path: 'child1', component: Child1Component },
{ path: 'child2', component: Child2Component },
{ path: '', redirectTo: '/child1', pathMatch: 'full' },
]}
];
并向您的父组件添加另一个 <router-outlet></router-outlet>
。我创建了一个 STACKBLITZ 来说明它。为了简单起见,所有组件都在同一个 ts 文件中。
您可以在 official site 阅读更多内容。