You can use the object windowwithout importing anything, but just using it in typescript code:
import { Component } from "@angular/core";
@Component({
templateUrl:"home.html"
})
export class HomePage {
public foo: string;
constructor() {
window.localStorage.setItem('foo', 'bar');
this.foo = window.localStorage.getItem('foo');
}
}
You can also wrap an object windowinside a service so that you can then mock it for testing purposes.
A naive implementation would be:
import { Injectable } from '@angular/core';
@Injectable()
export class WindowService {
public window = window;
}
You can then provide this when you download the application so that it is available everywhere.
import { WindowService } from './windowservice';
bootstrap(AppComponent, [WindowService]);
And just use it in your components.
import { Component } from "@angular/core";
import { WindowService } from "./windowservice";
@Component({
templateUrl:"home.html"
})
export class HomePage {
public foo: string;
constructor(private windowService: WindowService) {
windowService.window.localStorage.setItem('foo', 'bar');
this.foo = windowService.window.localStorage.getItem('foo');
}
}
, .