This currently works for me (2018-03, angular 5.2 with AoT, tested in angular-cli and custom web package build):
First, create an injection service that provides a link to the window:
import { Injectable } from '@angular/core'; // This interface is optional, showing how you can add strong typings for custom globals. // Just use "Window" as the type if you don't have custom global stuff export interface ICustomWindow extends Window { __custom_global_stuff: string; } function getWindow (): any { return window; } @Injectable() export class WindowRefService { get nativeWindow (): ICustomWindow { return getWindow(); } }
Now register this service in your root AppModule so that it can be deployed everywhere:
import { WindowRefService } from './window-ref.service'; @NgModule({ providers: [ WindowRefService ], ... }) export class AppModule {}
and then later where you need to enter window :
import { Component} from '@angular/core'; import { WindowRefService, ICustomWindow } from './window-ref.service'; @Component({ ... }) export default class MyCoolComponent { private _window: ICustomWindow; constructor ( windowRef: WindowRefService ) { this._window = windowRef.nativeWindow; } public doThing (): void { let foo = this._window.XMLHttpRequest; let bar = this._window.__custom_global_stuff; } ...
You can also add nativeDocument and other global variables to this service in the same way if you use them in your application.
edit: Updated with the offer of Truhaynets. edit2: updated for angular 2.1.2 edit3: added note AoT edit4: added workaround of any type edit5: updated solution for using WindowRefService, which fixes the error received when using the previous solution with another assembly edit6: added example of custom typing Window
elwyn May 12 '16 at 3:51 am 2016-05-12 03:51
source share