angulartypescriptangular-routingangular17angular-standalone-components

Angular 17 Module to Standalone Conversion. How should I setup main.ts or app.config.ts?


I'm trying to change my Angular 17 project to be a standalone project. But some of the fundamental files are different than how they are defined in tutorials and other people's projects. I didn't have app.config.ts at all, but most people are saying to put the routing configuration there. I created app.config.ts manually and added:

import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { routes } from './app/app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideHttpClient()
  ]
};

Routing doesn't seem to work with this configuration, but it does work in my main.ts with the following setup. Just not for using routerLink like: <!-- <a routerLink="/charts">Charts</a> -->

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { importProvidersFrom } from '@angular/core';
import { AppComponent } from './app/app.component';
import { FormsModule } from '@angular/forms';
import { DictionaryToolService } from './app/services/dictionary-tool.service';
import { provideClientHydration, BrowserModule, bootstrapApplication } from '@angular/platform-browser';

import { provideRouter } from '@angular/router';
import { routes } from './app/app.routes';

bootstrapApplication(AppComponent, {
    providers: [
        provideRouter(routes),
        importProvidersFrom(BrowserModule, FormsModule),
        provideClientHydration(),
        DictionaryToolService
    ]
})
  .catch(err => console.error(err));

Which of these files should I be using and how are they connecting the rest of the project? Also interested if the routerLink issue is related to which file it's in.


Solution

  • You have two options, for better readability we can move the global providers to a separate app.config.ts, but we must use this inside the main.ts for the providers to be read.

    ...
    import { appConfig } from '<<path to app config>>/app.config.ts'
    ...
    
    bootstrapApplication(AppComponent, appConfig)
      .catch(err => console.error(err));
    

    If we do not use this file in the main.config.ts, the files is basically useless.


    Or we just define all the providers in the main.ts and remove this app.config.ts, which is good enough for less number of providers.

    ...
    ...
    bootstrapApplication(AppComponent, {
        providers: [
            provideRouter(routes),
            importProvidersFrom(BrowserModule, FormsModule),
            provideClientHydration(),
            DictionaryToolService
        ]
    })
      .catch(err => console.error(err));