角路由未显示组件内容

时间:2020-09-17 12:33:29

标签: angular angular-routing

我在这里创建了一个项目示例:stackblitz

我在Angular应用程序中实现了路由。作为其一部分,我编写了上面的 Stackblitz

在该样本上有两个可用组件:

  1. Appcomponent
  2. LoginComponet

默认情况下,每当我们将URL设置为LoginComponent时,它都应转到/home,然后应呈现AppComponent

app-routing.module.ts

const appRoutes:Routes=[
  { path: '', component: LoginComponent },
  { path: 'home', component: AppComponent },
  { path: '**', redirectTo: '/not-found', pathMatch: 'full' }  
]

App.component.html

<div class="container">
  <h2> Hello App component</h2>
</div>
<router-outlet></router-outlet>

但是问题是默认情况下,它在同一页面中显示appcomponentLoginComponet内容。

有人可以帮忙吗?

谢谢

2 个答案:

答案 0 :(得分:3)

好的,根据我们的评论,我发现了问题。从<router-outlet></router-outlet>中删除<app-root></app-root>login.component.html,如果还有component.html以外的其他app.component.html,则删除{在您的设计中,Yo在整个应用程序中只需要一个<router-outlet></router-outlet>。在app.component.html中,您只需要拥有<router-outlet></router-outlet>即可。如果app.component.html中还有其他内容,请将其提取出来并放入带有新路径的新组件中。没关系。

答案 1 :(得分:0)

启动Angular应用程序时,默认情况下会启动与AppComponent相对应的根组件。

然后,它加载相应html页面的所有元素。当您在<router-outlet> </router-outlet>之前有内容时,它将显示它们。

您可以找到一个很好的示例,说明如何将路由添加到应用程序angular TOH

因此,您必须在默认组件'AppComponent'中放置任何内容,并创建另一个将以'home'路线显示的组件。

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'home', component: ${new Component} },
  { path: '', pathMatch: 'full', redirectTo: 'login' },
];