Angular's application and platform management APIs provide comprehensive control over application lifecycle, bootstrapping, platform abstraction, and initialization processes.
Core classes and functions for managing Angular application instances.
/**
* Reference to running Angular application instance
*/
class ApplicationRef {
/**
* Bootstrap a component as root component
* @param componentOrFactory - Component type or factory
* @param rootSelectorOrNode - Selector or DOM node to attach to
* @returns Component reference
*/
bootstrap<C>(
componentOrFactory: ComponentFactory<C> | Type<C>,
rootSelectorOrNode?: string | any
): ComponentRef<C>;
/**
* Manually trigger change detection across the application
*/
tick(): void;
/**
* Attach a view to the application
* @param viewRef - View reference to attach
*/
attachView(viewRef: ViewRef): void;
/**
* Detach a view from the application
* @param viewRef - View reference to detach
*/
detachView(viewRef: ViewRef): void;
/**
* Get all attached views
*/
get viewCount(): number;
/**
* Array of all root components
*/
readonly components: ComponentRef<any>[];
/**
* Whether application is destroyed
*/
readonly isStable: Observable<boolean>;
/**
* Observable that emits when application becomes stable
*/
readonly onDestroy: Observable<void>;
}
/**
* Configuration object for application setup
*/
interface ApplicationConfig {
/** Array of providers for the application */
providers: Provider[];
}
/**
* Merge multiple application configurations
* @param configs - Application configurations to merge
* @returns Merged application configuration
*/
function mergeApplicationConfig(...configs: ApplicationConfig[]): ApplicationConfig;
/**
* Options for application bootstrapping
*/
interface BootstrapOptions {
/** Whether to enable development mode checks */
ngZoneEventCoalescing?: boolean;
/** Whether to enable zone patching */
ngZoneRunCoalescing?: boolean;
}Platform abstraction layer for running Angular on different environments.
/**
* Reference to current platform providing core services
*/
abstract class PlatformRef {
/**
* Bootstrap a module on this platform
* @param moduleType - Module type to bootstrap
* @param compilerOptions - Optional compiler options
* @returns Promise resolving to module reference
*/
abstract bootstrapModule<M>(
moduleType: Type<M>,
compilerOptions?: (CompilerOptions & BootstrapOptions) | CompilerOptions[]
): Promise<NgModuleRef<M>>;
/**
* Bootstrap a standalone component on this platform
* @param component - Component type to bootstrap
* @param options - Bootstrap options
* @returns Promise resolving to component reference
*/
abstract bootstrapApplication(
component: Type<any>,
options?: ApplicationConfig
): Promise<ApplicationRef>;
/**
* Destroy the platform and cleanup resources
*/
abstract destroy(): void;
/**
* Get the platform injector
*/
abstract get injector(): Injector;
/**
* Whether platform is destroyed
*/
abstract get destroyed(): boolean;
}
/**
* Create new platform with specified providers
* @param injector - Injector with platform providers
* @returns Platform reference
*/
function createPlatform(injector: Injector): PlatformRef;
/**
* Create platform factory function
* @param parentPlatformFactory - Optional parent platform factory
* @param name - Platform name for debugging
* @param providers - Platform providers
* @returns Platform factory function
*/
function createPlatformFactory(
parentPlatformFactory: PlatformFactory | null,
name: string,
providers: StaticProvider[]
): PlatformFactory;
/**
* Get reference to current platform
* @returns Current platform reference or null
*/
function getPlatform(): PlatformRef | null;
/**
* Assert that platform exists, throw if not
* @returns Current platform reference
*/
function assertPlatform(): PlatformRef;
/**
* Destroy current platform and cleanup resources
*/
function destroyPlatform(): void;
/**
* Provide platform initializer functions
* @param callback - Initialization function
* @returns Platform providers
*/
function providePlatformInitializer(callback: () => void): Provider[];
/**
* Platform factory function type
*/
type PlatformFactory = (extraProviders?: StaticProvider[]) => PlatformRef;Services and tokens for managing application startup and initialization.
/**
* Service tracking application initialization status
*/
class ApplicationInitStatus {
/** Whether application initialization is done */
readonly done: boolean;
/** Promise that resolves when initialization is complete */
readonly donePromise: Promise<any>;
}
/**
* Provide application initializer functions
* @param initializerFn - Initialization function (can return Promise/Observable)
* @returns Application providers
*/
function provideAppInitializer(
initializerFn: () => Observable<unknown> | Promise<unknown> | void
): EnvironmentProviders;
/**
* Token for application initialization functions
*/
const APP_INITIALIZER: InjectionToken<(() => Observable<unknown> | Promise<unknown> | void)[]>;
/**
* Token for application bootstrap listeners
*/
const APP_BOOTSTRAP_LISTENER: InjectionToken<((compRef: ComponentRef<any>) => void)[]>;Standard injection tokens for application configuration and metadata.
/** Token for unique application identifier */
const APP_ID: InjectionToken<string>;
/** Token for package root URL */
const PACKAGE_ROOT_URL: InjectionToken<string>;
/** Token for platform identifier (browser, server, etc.) */
const PLATFORM_ID: InjectionToken<Object>;
/** Token for platform initialization functions */
const PLATFORM_INITIALIZER: InjectionToken<(() => void)[]>;
/** Token for animation module type */
const ANIMATION_MODULE_TYPE: InjectionToken<'BrowserAnimations' | 'NoopAnimations' | null>;
/** Token for Content Security Policy nonce */
const CSP_NONCE: InjectionToken<string | null>;
/** Token for the Document object */
const DOCUMENT: InjectionToken<Document>;
/** Token for HTTP request object (SSR) */
const REQUEST: InjectionToken<any>;
/** Token for request context (SSR) */
const REQUEST_CONTEXT: InjectionToken<unknown>;
/** Token for response initialization (SSR) */
const RESPONSE_INIT: InjectionToken<ResponseInit>;Functions for dynamically creating components and modules.
/**
* Create component instance dynamically
* @param component - Component type to create
* @param options - Creation options
* @returns Component reference
*/
function createComponent<C>(
component: Type<C>,
options: {
environmentInjector: EnvironmentInjector;
hostElement?: Element;
elementInjector?: Injector;
projectableNodes?: Node[][];
}
): ComponentRef<C>;
/**
* Reflect component metadata for introspection
* @param component - Component type to reflect
* @returns Component mirror with metadata
*/
function reflectComponentType<C>(component: Type<C>): ComponentMirror<C> | null;
/**
* Component metadata mirror for reflection
*/
interface ComponentMirror<C> {
/** Component type */
readonly type: Type<C>;
/** Component selector */
readonly selector: string;
/** Input properties */
readonly inputs: Array<{propName: string; templateName: string}>;
/** Output properties */
readonly outputs: Array<{propName: string; templateName: string}>;
/** Whether component is standalone */
readonly isStandalone: boolean;
}
/**
* Create NgModule instance with injector
* @param moduleType - Module type to create
* @param parentInjector - Parent injector
* @returns Module reference
*/
function createNgModule<T>(
moduleType: Type<T>,
parentInjector?: Injector
): NgModuleRef<T>;
/**
* Create NgModule reference with providers
* @param moduleType - Module type
* @param parentInjector - Parent injector
* @param additionalProviders - Additional providers
* @returns Module reference
*/
function createNgModuleRef<T>(
moduleType: Type<T>,
parentInjector: Injector,
additionalProviders?: StaticProvider[]
): NgModuleRef<T>;
/**
* Create environment injector
* @param providers - Environment providers
* @param parent - Parent injector
* @param debugName - Debug name
* @returns Environment injector
*/
function createEnvironmentInjector(
providers: Array<Provider | EnvironmentProviders>,
parent: Injector,
debugName?: string
): EnvironmentInjector;Functions for controlling development mode features and optimizations.
/**
* Enable production mode optimizations
*/
function enableProdMode(): void;
/**
* Check if running in development mode
* @returns True if in development mode
*/
function isDevMode(): boolean;
/**
* Configure check no changes behavior in development
* @param config - Configuration options
* @returns Environment providers
*/
function provideCheckNoChangesConfig(config: {
/** How often to run check no changes */
frequency?: 'always' | 'once' | 'never';
}): EnvironmentProviders;Global error handling services and providers.
/**
* Service for handling uncaught errors
*/
abstract class ErrorHandler {
/**
* Handle an error
* @param error - Error to handle
*/
abstract handleError(error: any): void;
}
/**
* Provide global error listeners for browser environment
* @returns Environment providers for error handling
*/
function provideBrowserGlobalErrorListeners(): EnvironmentProviders;Service for transferring state between server and client in SSR applications.
/**
* Service for transferring state between server and client
*/
class TransferState {
/**
* Get value by key
* @param key - State key
* @param defaultValue - Default value if key not found
* @returns Stored value or default
*/
get<T>(key: StateKey<T>, defaultValue: T): T;
/**
* Set value by key
* @param key - State key
* @param value - Value to store
*/
set<T>(key: StateKey<T>, value: T): void;
/**
* Remove value by key
* @param key - State key
*/
remove<T>(key: StateKey<T>): void;
/**
* Check if key exists
* @param key - State key
* @returns True if key exists
*/
hasKey<T>(key: StateKey<T>): boolean;
/**
* Serialize state to HTML
* @returns HTML script tag with state
*/
toHtml(): string;
}
/**
* Create type-safe key for transfer state
* @param key - String key identifier
* @returns Type-safe state key
*/
function makeStateKey<T = void>(key: string): StateKey<T>;
/**
* Type-safe key for transfer state values
*/
interface StateKey<T> {
/** Unique key identifier */
readonly key: string;
}import { bootstrapApplication, ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { AppComponent } from './app.component';
import { routes } from './app.routes';
// Application configuration
const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(),
provideZoneChangeDetection({ eventCoalescing: true }),
// Custom providers
{ provide: 'API_URL', useValue: 'https://api.example.com' }
]
};
// Bootstrap standalone application
bootstrapApplication(AppComponent, appConfig)
.then(() => console.log('Application started'))
.catch(err => console.error('Bootstrap failed:', err));import {
createPlatformFactory,
createPlatform,
destroyPlatform,
getPlatform,
PLATFORM_INITIALIZER
} from '@angular/core';
// Create custom platform factory
const customPlatformFactory = createPlatformFactory(
null, // no parent platform
'custom',
[
{ provide: 'PLATFORM_CONFIG', useValue: { debug: true } },
{
provide: PLATFORM_INITIALIZER,
useValue: () => console.log('Platform initialized'),
multi: true
}
]
);
// Use platform
function initializePlatform() {
// Check if platform exists
const existingPlatform = getPlatform();
if (existingPlatform) {
destroyPlatform();
}
// Create new platform
const platform = customPlatformFactory();
// Bootstrap application on platform
return platform.bootstrapApplication(AppComponent, appConfig);
}import {
provideAppInitializer,
ApplicationInitStatus,
inject
} from '@angular/core';
// Configuration service
@Injectable({ providedIn: 'root' })
export class ConfigService {
private config: any = null;
async loadConfig(): Promise<void> {
const response = await fetch('/api/config');
this.config = await response.json();
console.log('Configuration loaded:', this.config);
}
getConfig() {
return this.config;
}
}
// User service that depends on configuration
@Injectable({ providedIn: 'root' })
export class UserService {
private configService = inject(ConfigService);
private initStatus = inject(ApplicationInitStatus);
async getCurrentUser() {
// Wait for app initialization to complete
await this.initStatus.donePromise;
const config = this.configService.getConfig();
return fetch(`${config.apiUrl}/user/current`);
}
}
// Bootstrap with initializers
const appConfig: ApplicationConfig = {
providers: [
// App initializer that runs before application starts
provideAppInitializer(() => {
const configService = inject(ConfigService);
return configService.loadConfig();
}),
// Multiple initializers run in parallel
provideAppInitializer(() => {
console.log('Another initializer');
return Promise.resolve();
}),
// Other providers...
provideRouter(routes)
]
};import {
createComponent,
EnvironmentInjector,
Component,
ViewContainerRef,
inject
} from '@angular/core';
@Component({
selector: 'app-dynamic',
template: '<p>I am a dynamic component!</p>'
})
export class DynamicComponent {
data = inject('DYNAMIC_DATA', { optional: true });
}
@Component({
selector: 'app-container',
template: '<div #container></div>'
})
export class ContainerComponent {
private environmentInjector = inject(EnvironmentInjector);
private viewContainer = inject(ViewContainerRef);
createDynamicComponent(): void {
// Create component with custom injector
const componentRef = createComponent(DynamicComponent, {
environmentInjector: this.environmentInjector,
hostElement: this.viewContainer.element.nativeElement,
elementInjector: Injector.create({
providers: [
{ provide: 'DYNAMIC_DATA', useValue: { message: 'Hello from dynamic component!' } }
],
parent: this.environmentInjector
})
});
// Attach to view
this.viewContainer.insert(componentRef.hostView);
// Cleanup when needed
setTimeout(() => {
componentRef.destroy();
}, 5000);
}
}import { ErrorHandler, Injectable, inject } from '@angular/core';
@Injectable()
export class GlobalErrorHandler extends ErrorHandler {
override handleError(error: any): void {
console.error('Global error caught:', error);
// Send to logging service
// this.loggingService.logError(error);
// Show user-friendly message
// this.notificationService.showError('Something went wrong');
// Call default handler
super.handleError(error);
}
}
// Bootstrap with custom error handler
const appConfig: ApplicationConfig = {
providers: [
{ provide: ErrorHandler, useClass: GlobalErrorHandler },
provideBrowserGlobalErrorListeners(),
// Other providers...
]
};import {
TransferState,
makeStateKey,
inject,
isPlatformBrowser,
PLATFORM_ID
} from '@angular/core';
const USERS_KEY = makeStateKey<User[]>('users');
@Injectable({ providedIn: 'root' })
export class DataService {
private transferState = inject(TransferState);
private platformId = inject(PLATFORM_ID);
private http = inject(HttpClient);
getUsers(): Observable<User[]> {
// Check if data exists in transfer state (from SSR)
if (this.transferState.hasKey(USERS_KEY)) {
const users = this.transferState.get(USERS_KEY, []);
this.transferState.remove(USERS_KEY);
return of(users);
}
// Fetch from server
return this.http.get<User[]>('/api/users').pipe(
tap(users => {
// Store in transfer state if on server
if (!isPlatformBrowser(this.platformId)) {
this.transferState.set(USERS_KEY, users);
}
})
);
}
}