项目从 angular 15 升级到 angular 19 之后,将 component 迁移到 standalone component,ng build 已经没有任何错误,但运行时通过 ViewChild 加载的 component 没有任何显示
export class AppLayoutComponent implements OnInit, OnDestroy {
@ViewChild('sidebar', {
read: ViewContainerRef,
static: true,
})
}
请问如何解决这个问题?
How to use nested routes in standalone components?
是 RouterModule.forChild
部分没有迁移过来引起的
@NgModule({
imports: [
RouterModule.forChild([{ path: '', component: PostsEntryComponent, children: routes }]),
]
});
In module-based applications it’s been done by using loadChildren function to load NgModule which imports RouterModule defining routes using forChild static method
尝试下面这样迁移 RouterModule.forChild
,但不起作用,没有加载 PostsEntryComponent
app.routes.ts
export const routes: Routes = [
{
path: 'posts',
loadChildren: () => import('./pages/posts/posts.routes').then(m => m.POSTS_ROUTES),
}
]
posts.routes.ts
export const POSTS_ROUTES: Routes = [
{
path: '',
component: PostMainComponent,
children: [{
path: '',
loadComponent: () => import('./posts-entry.component').then(m => m.PostsEntryComponent),
}]
}
]
终于解决了!是路由的上下级关系弄反了。
不是
PostMainComponent
|
PostsEntryComponent
而是
PostsEntryComponent
|
PostMainComponent
posts.routes.ts 的正确配置
export const POSTS_ROUTES: Routes = [
{
path: '',
component: PostsEntryComponent,
children: [
{
path: '',
loadComponent: () => import('./post-main.component').then(x => x.PostMainComponent),
}
]
}
]
关于 ViewChild,可以看这篇博文 Understanding the ViewChild and ViewChildren decorators in Angular 10
– dudu 6天前How to load routing module in angular 17 for RouterModule.forChild
– dudu 6天前How to implement nested routing in Angular (16+) using stand-alone components
– dudu 6天前Where to import child route in standalone components
– dudu 6天前