繁体   English   中英

Angular 路由未显示组件内容

[英]Angular routing is not showing the component content

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

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

在该示例中,有两个组件可用:

  1. 应用组件
  2. 登录组件

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

app-routing.module.ts

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

应用组件.html

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

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

任何人都可以帮忙吗?

谢谢

好的,根据我们的评论,我遇到了问题。 login.component.html删除<router-outlet></router-outlet><app-root></app-root> ,如果除了app.component.html之外的任何其他component.html中有.

在您的设计中,整个应用程序中只需要一个<router-outlet></router-outlet> app.component.html你只需要<router-outlet></router-outlet>而没有别的。 如果app.component.html有一些其他内容, app.component.html提取它们并放入具有新路由的新组件中。 应该没问题。

当您启动 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' }, ];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM