Sub topic 5
How the application starts: main.ts and the application config
This chapter assumes you have created a workspace with ng new, can read basic TypeScript, and know what a component and a decorator are. It covers the path from the browser loading your page to the first component rendering. It focuses on src/main.ts and src/app/app.config.ts.
The startup path
An Angular application does not start itself. The build tool bundles your code, and index.html loads those bundles. One file, main.ts, must ask Angular to create the application. The CLI is told which file this is by the browser option in angular.json.
The sequence looks like this:
index.html and the host element
src/index.html is a plain HTML file. It contains no application logic, only a placeholder element whose tag name matches the root component's selector:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyApp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<app-root></app-root>
</body>
</html>You do not add <script> tags yourself. During a build, the CLI injects the references to the generated bundles. The <base href="/"> tag matters for routing: the router uses it to build and resolve URLs.
main.ts
The entry point is short:
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));Newer CLI versions name the root file and class app.ts and App instead of app.component.ts and AppComponent. The structure is the same.
bootstrapApplication takes two arguments:
- The root component. Angular looks at its
selector(for exampleapp-root), finds a matching element inindex.html, and renders the component there. - An optional configuration object. Its
providersarray registers services and features that the whole application can use.
The function returns a promise. Bootstrapping can fail, for example when a provider throws while it is being created or when no element matches the root selector. The .catch logs such errors to the console. Without it, a failure would surface only as an unhandled promise rejection.
What main.ts should not contain
Keep main.ts small. It runs once, before any component exists, so it is the wrong place for feature logic. Put configuration in app.config.ts. Put behavior in components and services.
The application config
src/app/app.config.ts exports an object typed as ApplicationConfig:
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes)],
};ApplicationConfig has a providers property. Each entry tells Angular's dependency injection system how to create something. Here, provideRouter(routes) registers the router and gives it the route table from app.routes.ts.
Depending on the options you chose in ng new, the generated file may contain more entries. Common ones include a change detection setup and server-side rendering support. Treat the list as the single place where application-wide behavior is switched on.
Why separate config from main.ts
Splitting the config into its own file has practical benefits:
- Tests can import
appConfigand reuse or extend it. - Server-side rendering uses a second entry point that merges the same config with server-only providers.
main.tsstays readable as the provider list grows.
Providers and the root injector
When bootstrapApplication runs, Angular builds an environment injector from the providers array. Services registered there are available to every component, directive, and pipe in the application.
A provide... function is a convention for registering a feature. Each one returns a set of providers so you do not need to know the internal tokens. Common examples:
| Function | Purpose |
|---|---|
| `provideRouter(routes)` | Registers the router with a route table |
| `provideHttpClient()` | Makes `HttpClient` injectable |
| `provideAnimations()` | Enables the animations system |
| `provideZoneChangeDetection({ eventCoalescing: true })` | Configures how Angular detects changes after events |
Adding a feature means adding one entry:
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withFetch } from '@angular/common/http';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(withFetch()),
],
};Here withFetch() is a feature function. It adjusts how provideHttpClient behaves, in this case by using the browser's fetch API for requests.
Services that are not in the config
Most services do not need to be listed in appConfig. A service declared with @Injectable({ providedIn: 'root' }) registers itself in the root injector the first time it is injected. Use the providers array for things that need configuration, such as the router, or for things that must be set up before the application runs.
Running code before the app renders
Sometimes you need to run setup work during startup, such as loading a configuration file. The provideAppInitializer function (available in recent Angular versions) registers a function that Angular runs during bootstrapping:
import { ApplicationConfig, inject, provideAppInitializer } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { SettingsService } from './settings.service';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideAppInitializer(() => inject(SettingsService).load()),
],
};If the function returns a promise or observable, Angular waits for it to finish before rendering the root component. Use this sparingly. A slow initializer delays the first paint for every user.
Older projects: NgModule bootstrapping
Projects created before Angular 17, and some later ones that opted out of standalone components, start with platformBrowserDynamic().bootstrapModule(AppModule) in main.ts. The root AppModule lists declarations, imports, and providers. The standalone approach replaces that module with the application config. The next chapters cover standalone components in more detail. For now, recognize both forms so you can read either kind of codebase.
Common errors
| Symptom | Likely cause |
|---|---|
| Console error: `NG05104: Root element was not found` | The root component's `selector` does not match any element in `index.html` |
| `NullInjectorError: No provider for HttpClient` | `provideHttpClient()` is missing from `appConfig.providers` |
| Router links do nothing, or `Router` cannot be injected | `provideRouter` is missing or the config was not passed to `bootstrapApplication` |
| Blank page and no error | The `.catch` was removed, or an error occurred before bootstrapping, so check the browser console and the terminal running `ng serve` |
| App loads but URLs break on refresh | Missing or wrong `<base href>` in `index.html` |
Exercise
You add provideHttpClient() to a component's providers array, and another component in a different part of the app still reports NullInjectorError: No provider for HttpClient. Where should the call go so the whole application can use HttpClient, and why does the fix work?
Show answer
Put provideHttpClient() in the providers array of appConfig in app.config.ts, which is passed to bootstrapApplication. Providers in that array go into the environment injector at the root, which every component can reach. A provider in one component's providers array is visible only to that component and its children.
Exercise
What are the two arguments of bootstrapApplication in main.ts, and what does Angular use the first one's selector for?
Show answer
The first argument is the root component and the second is the application config with the providers array. Angular uses the selector to find the matching element in index.html, such as <app-root>, and renders the root component inside it.