You can access window object in Angular this way. Firsly we have to create a service. Since our Angular application isn’t only designed for running within your browser, but on mobiles platforms, 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.
import { Injectable } from '@angular/core';
function _window() : any {
// return the global native browser window object
return window;
}
@Injectable({
providedIn: root
})
export class WindowRef {
get nativeWindow() : any {
return _window();
}
}
And we can simply call that in our component like so:
import { WindowRef } from './WindowRef';
@Component({...})
class MyComponent {
constructor(private winRef: WindowRef) {
// getting the native window obj
console.log('Native window obj', winRef.nativeWindow);
}
}
Now create a function that handles the newtab action
function openInNewTab(url) {
let newTab = this.winRef.open('https://stackoverflow.com/questions/61488800/kill-angular-in-chrome', '_blank');
newTab.focus(); //=====> Focus new tab
let currentTab = this.winRef.open("", "_self");
currentTab.document.write("");
currentTab.close();
}