Angular 路由未显示组件内容

Angular routing is not showing the component content

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

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

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

  1. Appcomponent
  2. LoginComponet

默认情况下,只要我们将 URL 设为 /home,它就应该转到 LoginComponent,然后它应该呈现 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 内容。

有人可以帮忙吗?

谢谢

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

好的,根据我们的评论,我发现了问题。从 login.component.html 中删除 <router-outlet></router-outlet><app-root></app-root>,如果 component.html 中除 app.component.html.

之外还有任何其他 component.html

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