为独立组件创建一个模块并在其中添加路由。
示例代码:
首先,创建一个新的模块来包含独立组件,命名为“StandaloneModule”。
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { StandaloneComponent } from './standalone.component';
@NgModule({
declarations: [
StandaloneComponent
],
imports: [
CommonModule,
RouterModule.forChild([
{ path: '', component: StandaloneComponent }
])
]
})
export class StandaloneModule { }
在上面的示例中,我们导入了“RouterModule”,以便我们可以使用路由。然后,我们将“RouterModule.forChild()”添加到模块的“imports”数组中,并为独立组件添加一个路由:“{ path: '', component: StandaloneComponent }”。
请注意,“RouterModule.forChild()”不同于“RouterModule.forRoot()”,后者用于应用的根模块。
最后,将“StandaloneModule”导入到使用独立组件的模块中。
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { StandaloneModule } from './standalone/standalone.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
CommonModule,
StandaloneModule // 添加 StandaloneModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
现在,你的独立组件就可以使用路由了。