Sub topic 7
How the App Starts: main.ts and app.config.ts
In the last chapter, ng serve displayed your app in the browser. This chapter covers what happens between the moment the browser loads the page and the moment your root component appears on screen. You will trace the startup path through index.html, main.ts, and app.config.ts, and see what each file contributes.
This chapter assumes you have a project generated with ng new, as covered earlier. It also assumes you can read TypeScript imports and decorators, and that you know roughly what a promise is.
The Three Files That Start Everything
Three files cooperate when the app starts:
| File | Role | Who reads it |
|---|---|---|
| `src/index.html` | The single HTML page. It contains the host element `<app-root>`. | The browser |
| `src/main.ts` | The entry point. It calls `bootstrapApplication`. | The build tool, then the browser as JavaScript |
| `src/app/app.config.ts` | The application-wide providers, such as the router and HTTP client. | `bootstrapApplication` |
The root component (App in src/app/app.ts) is the fourth piece. Its selector must match the host element in index.html.
Step 1: index.html Provides the Host Element
The CLI generates a minimal page:
<!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">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>There is no <script> tag in the source. At build time the CLI injects the script tags for the compiled bundles. <app-root> is an unknown element to the browser, so it renders nothing until Angular takes it over. The <base href="/"> tag tells the router how to resolve relative URLs, which matters once you add routes.
Step 2: main.ts Calls bootstrapApplication
The build configuration in angular.json names src/main.ts as the entry point (the browser option in recent CLI versions, main in older ones). Here is the generated file:
// src/main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { App } from './app/app';
bootstrapApplication(App, appConfig)
.catch((err) => console.error(err));bootstrapApplication takes two arguments:
- The root component class,
App. It must be a standalone component, which is the default for all components in current Angular versions. - An
ApplicationConfigobject. In practice this is a list of providers.
The function returns a Promise<ApplicationRef>. ApplicationRef is a handle to the running application. The .catch handler logs any error that occurs during startup. Without it, a failed bootstrap produces an unhandled promise rejection that is easy to miss.
Step 3: app.config.ts Supplies the Providers
A provider tells Angular's dependency injection system how to create a value when something asks for it. app.config.ts collects the providers that the whole application needs:
// src/app/app.config.ts
import {
ApplicationConfig,
provideBrowserGlobalErrorListeners,
} from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
],
};Each provideX() function returns a bundle of providers for a feature. provideRouter(routes) registers the router services and your route table. provideBrowserGlobalErrorListeners() forwards uncaught browser errors and unhandled promise rejections to Angular's ErrorHandler.
Depending on your CLI version, you may also see a change detection provider. Projects created by Angular 18 to 20 usually include provideZoneChangeDetection({ eventCoalescing: true }), which uses the Zone.js library to trigger updates. Projects created by Angular 21 and later are zoneless by default and omit it. Leave whatever the CLI generated in place unless you have a specific reason to change it.
Keeping this object in its own file, separate from main.ts, has a practical benefit. Server-side rendering and tests can reuse or extend the same configuration without duplicating the provider list.
Step 4: The Root Component Attaches to the Host
The root component looks like any other component:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
imports: [RouterOutlet],
templateUrl: './app.html',
styleUrl: './app.css',
})
export class App {
protected readonly title = signal('my-app');
}Angular searches the document for an element matching selector: 'app-root', creates the component, and renders its template inside that element. The imports array lists what the template uses. Here that is RouterOutlet, where routed pages will appear.
The Full Startup Sequence
Two details in this sequence matter in practice:
- The environment injector is built from
appConfig.providersbefore any component exists. Every service registered there is available to every component. - App initializers run before the root component is created. If an initializer returns a promise or observable, Angular waits for it to finish before rendering.
Running Code Before the First Render
Sometimes you need work done before the UI appears, such as loading runtime settings. provideAppInitializer registers a function for that step. The function runs in an injection context, so it can call inject().
// src/app/app.config.ts
import {
ApplicationConfig,
provideAppInitializer,
provideBrowserGlobalErrorListeners,
} from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideAppInitializer(() => {
console.log('Initializing before first render');
return new Promise<void>((resolve) => setTimeout(resolve, 500));
}),
],
};Run ng serve and watch the page. The root component appears about half a second after the log message. provideAppInitializer is available from Angular 19. Older code uses the APP_INITIALIZER token for the same purpose.
Adding Features: Where Providers Go
When you add an Angular feature that needs app-wide services, its provideX() function goes into appConfig.providers. For example, to use HttpClient you add provideHttpClient():
import { provideHttpClient } from '@angular/common/http';
// inside appConfig.providers
provideHttpClient(),Some third-party libraries still export only an NgModule. You can extract that module's providers with importProvidersFrom(SomeModule) from @angular/core and put the result in the same array.
Common Startup Errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Blank page, console shows `NG05104: The selector "app-root" did not match any elements` | The selector in `app.ts` does not match the tag in `index.html` | Make the two names identical |
| `NullInjectorError: No provider for HttpClient!` | A feature's provider function is missing from `appConfig` | Add `provideHttpClient()` (or the relevant `provideX()`) |
| `NG0302` or `'router-outlet' is not a known element` | The template uses something the component did not import | Add it to the component's `imports` array |
| Blank page with no visible error | Bootstrap failed and the `.catch` was removed | Restore the `.catch` and check the console |
| Page stays blank for a long time | A slow or never-settling app initializer | Shorten it, add a timeout, or move the work after the first render |
The first two rows cover most startup problems. When the screen is blank, open the browser console before anything else. Angular's error codes link to explanation pages on angular.dev.
Key Points
- The browser loads
index.html, and the CLI-injected script runsmain.ts. bootstrapApplication(App, appConfig)builds the environment injector from the providers, runs initializers, then rendersAppinto<app-root>.app.config.tsis the single place for application-wide providers.- The root component's selector and the host element in
index.htmlmust match.
Exercise
You add a service that injects HttpClient, and the app now shows a blank page with "NullInjectorError: No provider for HttpClient!" in the console. Which file do you change, and what do you add?
Show answer
Change src/app/app.config.ts. Import provideHttpClient from '@angular/common/http' and add provideHttpClient() to the providers array of appConfig. Providers in that array are registered in the environment injector before any component is created, so every component and service can inject HttpClient.
Exercise
You rename the root component's selector from 'app-root' to 'my-root' but leave index.html unchanged. What happens at startup, and what are two ways to fix it?
Show answer
Angular cannot find a host element matching 'my-root', so bootstrapApplication rejects with error NG05104 and nothing renders. The .catch in main.ts logs it to the console. Fix it by changing the tag in index.html to <my-root></my-root>, or by changing the selector back to 'app-root'.
Exercise
An app initializer returns a promise that never resolves. Describe what the user sees and explain why, using the startup sequence.
Show answer
The user sees a blank page indefinitely. Angular waits for all app initializers to settle before it creates the root component, so the component is never created, the template is never rendered, and the bootstrap promise neither resolves nor rejects. No error appears unless the initializer logs one.