Angular 17路由异常:无法跳转至InicioComponent组件
Angular 17 路由配置问题:空路径无法渲染InicioComponent
我正在初学Angular 17,创建了第一个组件InicioComponent,但启动服务器后,网页显示的是app.component.html的内容,而非InicioComponent的内容。我已配置路由规则(将空路径指向InicioComponent),甚至尝试在路径前添加/,但均未生效。
以下是我的相关配置代码:
app.module.ts
import { BrowserModule } from "@angular/platform-browser"; import { NgModule } from "@angular/core"; import { FormsModule } from "@angular/forms"; import { HttpClient, HttpClientModule } from "@angular/common/http"; import {AppRoutingModule} from "./app-routing.module"; import { AppComponent } from "./app.component"; import { routing } from "./app.routes"; import { InicioComponent } from "./components/inicio/inicio.component"; @NgModule({ declarations: [ AppComponent, InicioComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, HttpClientModule, routing ], providers: [], bootstrap: [AppComponent] }) export class AppModule {}
app.routes.ts
import { Routes, RouterModule } from '@angular/router'; import { ModuleWithProviders } from '@angular/core'; import { InicioComponent } from './components/inicio/inicio.component'; const routes: Routes = [ {path: '', component: InicioComponent} ] export const appRoutingProviders : any[] = []; export const routing: ModuleWithProviders<any> = RouterModule.forRoot(routes);//aca mandamos todas las rutas
请问我遗漏了什么配置?恳请各位提供帮助,谢谢!
解决方案
你遗漏了在app.component.html中添加路由出口标签<router-outlet>,Angular需要通过这个标签来渲染匹配路由规则的组件内容。
修改app.component.html,确保包含以下内容:
<router-outlet></router-outlet>
另外补充:在Angular 17中官方更推荐使用独立组件+新路由配置方式,但基于你当前NgModule的写法,添加<router-outlet>即可解决问题。
内容的提问来源于stack exchange,提问作者Hugo Bustamante
相关产品推荐
相关产品推荐

