在Angular15中,要设置默认路由可以使用RouterModule.forRoot()和RouterModule.forChild()方法,以下是示例代码:
app-routing.module.ts:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '**', redirectTo: '' }
];
@NgModule({
imports: [ RouterModule.forRoot(appRoutes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
@NgModule({
imports: [
BrowserModule,
RouterModule,
AppRoutingModule
],
declarations: [
AppComponent,
HomeComponent,
AboutComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
在上述代码中,AppComponent是应用的根组件,home.component.ts和about.component.ts是两个要展示的组件,AppRoutingModule是应用的路由配置模块。在这里,空路径''被指定为默认路由,即访问应用时默认展示HomeComponent组件的内容。
注:以上代码均为示例代码,实际应用中需要根据具体情况进行修改。
上一篇:Angular15中的FontAwesome图标无法正常显示。
下一篇:Angular15中的NgRxstorestrictActionImmutability和strictStateImmutability错误