英文:
Routing in Angular 16 not working for Standalone Components
问题
这是您提供的内容的中文翻译:
代码 - https://github.com/suyashjawale/Angular16
我使用以下命令生成了我的Angular 16项目,并选择了启用路由。
ng new myapp --standalone
然后,我使用以下命令生成了其他组件:
ng g c components/home
因为我使用了 --standalone
选项,所以样板文件有所不同。例如,新增了文件 app.routes.ts
。
现在我想要实现路由,所以我将以下代码添加到 app.routes.ts
。
但是路由没有生效。我不知道为什么?我已经重新启动了应用程序,但仍然不起作用。所以我尝试了 loadComponent
的方式。但是仍然不起作用。以下是代码。
我是否做错了什么?在Angular 15中,这个方法可行。但是它使用了 app.routing.module.ts
。我已经重新启动了应用程序,但仍然不起作用。
FYI - 组件是独立的
英文:
Code - https://github.com/suyashjawale/Angular16
I have generated my Angular 16 project using following command and selected routing to yes.
ng new myapp --standalone
And then I generated other components using
ng g c components/home
Since, i used --standalone
the boilerplate files are different. (Eg. New file app.routes.ts)
Now I want to implement routing So I added the following code to app.routes.ts.
But the routing doesn't happen. Idk why?. I have restarted the app. still it doesn't work.
So i implemeted loadComponent. But still it doesn't work. Code below.
Am i doing anything wrong. It works with angular 15. But it has app.routing.module.ts. I have restarted the app but still it doesn't work.
FYI - component is standalone
答案1
得分: 1
代码部分不需要翻译。以下是翻译好的内容:
"The interesting part is the main.ts
. Here is a function called bootstrapApplication
. This should look like this:
bootstrapApplication(AppComponent, {
providers: [
importProvidersFrom(HttpClientModule),
provideRouter(APP_ROUTES),
[...]
]
});
Important, too (for Standalone Components in your case): In your app.component.ts
you need to import RouterLink
, too. If you wanna use RouterLinkActive
, too import it too:
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterLink, RouterLinkActive, RouterOutlet],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
APP_ROUTES are your routes: Routes [ { path..... } ]
"
英文:
The interesting part is the main.ts
. Here is a function called bootstrapApplication
. This should look like this:
bootstrapApplication(AppComponent, {
providers: [
importProvidersFrom(HttpClientModule),
provideRouter(APP_ROUTES),
[...]
]
});
Important, too (for Standalone Components in your case): In your app.component.ts
you need to import RouterLink
, too. If you wanna use RouterLinkActive
, too import it too:
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterLink, RouterLinkActive, RouterOutlet],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
APP_ROUTES are your routes: Routes [ { path..... } ]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论