簡體   English   中英

角度子路由加載父組件而不是子組件

[英]Angular child route loading parent instead of child component

我正在嘗試根據父子概念來導航我的 Angular 應用程序。 當我加載父組件而不是子組件時,但 url 似乎是

const appRoute: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'dashboard', component: DashboardComponent },
  {
    path: 'solutions', component: SolutionComponent,
    children: [
      { path: 'cog', component: CogComponent }
    ]
  },
  { path: 'portfolio', component: PortfolioComponent },
  { path: '**', component: PortfolioComponent }
];

當我運行solutions/cog它重定向到SolutionComponent但它應該加載CogComponent

編輯:1

它會在我使用時起作用

const appRoute: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'solutions', component: SolutionComponent },
  { path: 'solutions/cog', component: CogComponent },
  { path: 'portfolio', component: PortfolioComponent },
  { path: '**', component: PortfolioComponent }
];

但我希望它應該從上面的方法加載。

請幫助解決這個問題。

...
{
    path: 'solutions', component: SolutionComponent,
    children: [
        { path: 'cog', component: CogComponent }
    ]
},
...

由於您已經為路徑solutions聲明了一個component ,因此它顯示了SolutionComponent並且它將在嵌套的router-outlet中呈現CogComponent

{ path: 'dashboard', component: DashboardComponent },
{
    path: 'solutions'
    children: [
        { path: 'cog', component: CogComponent },
        { path: '', component: SolutionComponent, pathMatch: 'full'}
    ]
},
...

上面的路線應該按您的預期工作。

您的第二種方法有效,因為 Angular 將在父路由器插座本身中加載CogComponent模板。 如果那是您想要的,那么您可以采用這種方法。

但是,如果您想將SolutionComponent作為CogComponent的父級,則必須將<router-outlet></router-outlet>添加到solution.component.html

這是如何做:

...

<router-outlet></router-outlet>

這將告訴 Angular 它需要在其中加載CogComponent ,因為/cog/solution路由的子路由。


這是供您參考的工作示例 StackBlitz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM