3

I tried to put the following code to get a window object in angular 2:

      @Component({
          selector: 'app-slider',
          templateUrl: './slider.component.html',
          styleUrls: ['./slider.component.css'],
          providers: [
            SliderService, 
            { provide: "windowObject", useValue: window}
          ]
        })
        export class SliderComponent implements OnInit {
        
          sliderList: Slider[] = [];
        
          constructor( private _sliderservice:SliderService, @Inject("windowObject") private _window:window ) { }

Unfortunately it does not work.

raaaay
  • 496
  • 7
  • 14
Martin
  • 33
  • 1
  • 1
  • 5
  • I'm not sure this should be considered a duplicate. 1) The other question is specifically about an angular service, whereas this is more broad (to include e.g., angular components). 2) The other question is specifically about how to inject, whereas there may be occasions when injection is not needed. If either of these two points is true, this is not a duplicate, right? – Marcus Jun 10 '20 at 14:45

1 Answers1

2

You don't need a provider for that. window is a global object and is accessible directly in your class

Yaroslav Grishajev
  • 2,127
  • 17
  • 22
  • 3
    Using window from the global JS object will make your Angular app brittle and will not work if you ever want to do server side rendering. – LocalPCGuy Mar 03 '20 at 21:33
  • @LocalPCGuy honest question: would it still be brittle if you use the 'optional chaining' question mark? E.g., ```window?.navigator``` – Marcus Jun 10 '20 at 14:50
  • @Marcus no, that would guard against `window` being null. Or you could wrap code that uses `window` in an `if (window) {...}` guard. – LocalPCGuy Jun 10 '20 at 18:15
  • Except when it's undefined, yes, it's a global object – Captain Prinny Aug 12 '21 at 17:58