DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Testing Business Programs Without Constructing Domain Objects
  • Zone-Free Angular: Unlocking High-Performance Change Detection With Signals and Modern Reactivity
  • When Angular APIs Return 200 but the Frontend Is Already Failing Users
  • Why Angular Performance Problems Are Often Backend Problems

Trending

  • Building a Real Pipeline With senro: Monorepos, Caching, and Triggers
  • Kill the Worker, Keep the Research: Build a Recoverable LangGraph Agent on Temporal
  • Why Your AI Agent Works in the Demo and Fails in Production
  • The Twelve-Factor Agents: Building Production-Ready LLM Applications

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Frameworks
  4. Angular 2: How Do I Get a Reference to the Window Object?

Angular 2: How Do I Get a Reference to the Window Object?

Remember the $window object in Angular 1? Turned out to be quite useful from now and then. But what about Angular 2? $window doesn't exist there. What's the alternative? How can I inject the Window object into my Angular 2 components? Find out here!

By 
Juri Strumpflohner
·
Sep. 22, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
76.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Remember the $window object in Angular 1? Turned out to be quite useful from now and then. But what about Angular 2? $window doesn't exist there. What's the alternative? How can I inject the Window object into my Angular 2 components?

Referencing global browser objects like document or window directly from within your code is possible, but not encouraged and considered bad practice.

Especially since Angular 2 isn’t only designed to run within your browser, but also on mobile, the server or web workers where objects like window may not be available.

Therefore the suggested approach is to wrap such objects and inject them through the dependency injection mechanism. This way it is possible to change the concrete runtime instance of a given object based on the environment the Angular application is running. The result we wanna achieve is the following:

...
import { WindowRef } from './WindowRef';

@Component({...})
class MyComponent {

    constructor(private winRef: WindowRef) {
        // getting the native window obj
        console.log('Native window obj', winRef.nativeWindow);
    }

}

So let’s see.

Wrapping window

A very straightforward and easy way to wrap window is by creating an Angular 2 service. That’s as easy as creating an ES6 class and decorating it with @Injectable.

import { Injectable } from '@angular/core';

function _window() : any {
   // return the global native browser window object
   return window;
}

@Injectable()
export class WindowRef {
   get nativeWindow() : any {
      return _window();
   }
}

Register WindowRef as Provider

Great, so far we’ve wrapped our window object. We aren’t ready yet, however. We first need to register our injectable service. This is done by registering it on the NgModule’s providers array or directly on the component, based on the scope of our provider. Check out the official docs on providers for more details.

import { WindowRef } from './WindowRef';

...

@NgModule({
    ...
    providers: [ WindowRef ]
})
export class AppModule{}

Try It Yourself

Great, we’re ready. You can now inject the WindowRef into your Angular 2 components and get access to the native window object.

Here’s a Plunker to play around with:

https://plnkr.co/edit/9qmBCVrmBZj3mPQjM0Zc?p=preview

You want to register only events on window or document? Then you may want to read this also:

http://juristr.com/blog/2016/09/ng2-event-registration-document/

Object (computer science) AngularJS

Published at DZone with permission of Juri Strumpflohner. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Testing Business Programs Without Constructing Domain Objects
  • Zone-Free Angular: Unlocking High-Performance Change Detection With Signals and Modern Reactivity
  • When Angular APIs Return 200 but the Frontend Is Already Failing Users
  • Why Angular Performance Problems Are Often Backend Problems

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook