首页 新闻 会员 周边 捐助

Angular: 迁移到 Standalone Component 后 ViewChild 无法正常工作

0
悬赏园豆:30 [已解决问题] 解决于 2025-01-04 19:04

项目从 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?

dudu的主页 dudu | 高人七级 | 园豆:28727
提问于:2025-01-03 17:34
< >
分享
最佳答案
0

RouterModule.forChild 部分没有迁移过来引起的

@NgModule({
    imports: [
        RouterModule.forChild([{ path: '', component: PostsEntryComponent, children: routes }]),
    ]
});
dudu | 高人七级 |园豆:28727 | 2025-01-03 20:43

In module-based applications it’s been done by using loadChildren function to load NgModule which imports RouterModule defining routes using forChild static method

来自:Angular Router – everything you need to know about

dudu | 园豆:28727 (高人七级) | 2025-01-04 17:07

尝试下面这样迁移 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),
        }]
    }
]
dudu | 园豆:28727 (高人七级) | 2025-01-04 18:12

终于解决了!是路由的上下级关系弄反了。

不是

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),
            }
        ]
    }
]
dudu | 园豆:28727 (高人七级) | 2025-01-04 18:58
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册