Girish Ingle
Girish Ingle

Reputation: 130

window.onload not working in angular 4

I want to open a new window popup and as soon as the URL got load in the new popup window I want to close it.

This my component

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'app';

  ngOnInit():void{
    var popup=window.open('https://www.w3schools.com','newwindow','width=300,height=200');
    popup.onload=function(){
      alert("Hello");
      window.close();
    }
  }
}

In above code

popup.onload=function(){
   alert("Hello");
   window.close();
 }

is not working, there is no alert and also window didn't got close. but if I just do

popup.alert("Hello");
popup.close(); 

It work's. But I want to close the window when the whole URL got load i.e on onload() function.

Please provide some pointer regarding this issue.

Thanks in advance!

Upvotes: 4

Views: 12222

Answers (3)

JAC
JAC

Reputation: 295

The problem is you used "alert("Hello"); " and did not reference the popup. It should be

popup.onload=function(){
  alert("Hello");
  window.close();
}

Upvotes: 0

Shivanand Patil
Shivanand Patil

Reputation: 51

angular 2 app run on the different environment like web, mobile, server-side rendering so windows object may or may not be available there. so it's not the best approach to use windows object directly instead make service which returns windows object and simply substitute the service implementation according to the environment

@Injectable()
export class WindowRef {
    constructor() {}

    getNativeWindow() {
        return window;
    }
}

Upvotes: 0

Lokesh Kumar Meena
Lokesh Kumar Meena

Reputation: 501

Why you are using onLoad if you can You use ngAfterViewInit(). "Respond after Angular initializes the component's views and child views / the view that a directive is in."

popup: any;
ngOnInit():void{
this.popup=window.open('https://www.w3schools.com','newwindow','width=300,height=200');
}
ngAfterViewInit() {
this.popup.close();
}

import ngAfterViewInit and try if this works for you.

Upvotes: 2

Related Questions