Window
The Window provider offers a safe and consistent way to access the global window object across different platforms.
The WINDOW token is typed as Window | null. In the browser it resolves to the real window object, or null when the document has no window, and on the server it is always null rather than a partial DOM emulation. The contract is therefore deterministic: consumers either check for null explicitly, or read the token inside browser-only callbacks such as afterNextRender.
Provider Setup
Add provideWindow to the providers array of your application configuration. Other Core services depend on it:
import { provideWindow } from '@/app/core/window';
export const appConfig: ApplicationConfig = {
providers: [
provideWindow(),
// ...other providers
],
};Usage
To access the global window object, you can inject the WINDOW injection token into your services or components:
private window = inject(WINDOW);
scrollToTop() {
this.window?.scrollTo({ top: 0, behavior: 'smooth' });
} Code that should only run in the browser, such as measuring the viewport, fits in afterNextRender:
private window = inject(WINDOW);
private viewportWidth = signal(0);
constructor() {
afterNextRender(() => {
this.viewportWidth.set(this.window?.innerWidth ?? 0);
});
}