Launch a fresh window within a separate tab

I'm attempting to trigger a new window to open when the user clicks on a button using the following code:

protected assignActity(type: string): void {
    var newWindow = window.open('/#/link');
    this.Service.assignActivity(type).subscribe(res => {
      newWindow.location = '/#/link/' + res;
      console.log(res);
    })
  }

However, I'm encountering an error:

core.umd.js:3468 TypeError: Cannot read property 'open' of undefined

What steps should I take to correct this issue and make it functional?

Answer №1

The reason why the window variable is coming up as undefined is due to the fact that you have redefined a variable named window in the local scope.

Based on the scoping rules of javascript/typescript, the value of local variables is checked before accessing the global variable. Additionally, when a variable is first declared, it is automatically set to undefined, which explains the error message you are encountering.

To resolve this issue, all you need to do is change the name of the variable where you store the reference to the opened tab

var newWindow = window.open('some_url');

However, this method is not ideal for angular2 apps as they can operate in various environments like mobile devices or server-side rendering where the availability of the window object may vary. Moreover, mocking the window object for testing purposes would be quite challenging.

Instead, you can encapsulate the window object within a service and inject that service into your component. This allows you to easily swap out the service implementation based on the environment using Dependency Injection

The service file

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

    getNativeWindow() {
        return window;
    }
}

The component file

@Component({
  selector : 'demo',
  template : '<div> Demo </div>'
})
class DemoComponent {

   nativeWindow: any
   constructor( private winRef: WindowRef ) { 
       this.nativeWindow = winRef.getNativeWindow();
   }

    protected assignActity(type: string): void {
       var newWindow = this.nativeWindow.open('/#/link');
       this.Service.assignActivity(type).subscribe(res => {

       newWindow.location = '/#/link/' + res;
       console.log(res);
    })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Monitor constantly to determine if an element is within the visible portion of the screen

For a thorough understanding of my query, I feel the need to delve deeper. While I am well-versed in solving this issue with vanilla Javascript that is compatible with typescript, my struggle lies in figuring out how to invoke this function throughout th ...

Modify the HTML based on the width of $(window)

I have a header bar with three columns. When the window width is less than 767px, I need to change the content of these columns. HTML: <div class="header"> <div class="col-xs-4" id="tab1">Original Text</div> <div class="col-x ...

How to call a local method from catch in Angular 2+ without utilizing bind

I'm currently working on a situation where I need to call a method from a catch block in my authentication service. The purpose is to redirect the user to the login page and remove information from local storage if the server returns an error (e.g., 4 ...

Pass a string with quotation marks to a component input in Angular 6

Need help with passing a string input to a component: @Component({ selector: 'abcComponent' template: ` <div> .... </div>` }) export class AbcComponent { @Input() text:string; } I am trying to send a strin ...

Issue with separatorKeys functionality in ng2-tag-input

I've been experimenting with the ng2-tag-input module using a simple configuration: import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'search-form', template: `<tag-input [( ...

Issue with Angular 4: Radio button defaults not being set

After hardcoding the value in component.ts, I am able to see the pre-selected radio button. However, when attempting to retrieve the value from sessionStorage, it does not work as expected. The value is visible in the console though. Could someone please ...

switch between choosing, including, and deleting

Presenting a catalog of products, showcasing available products along with all related rate plans. Each rate plan includes a toggle button for adding the product + rate plan to the order. Below are the functions used to add and remove items from the order ...

CheckBox status is not reflecting changes

I'm currently developing a restaurant order application where users can select options using checkboxes. However, I've encountered an issue with the checkbox toggling when using state to manage it in my React code: import {useState} from "re ...

Develop a Typescript interface containing all the necessary properties for a specific JSX component

My goal is to create a ControlledInputComponent that consists of a label and an input inside a div. I aim to make it highly customizable as I plan on using it in various ways. At the moment, I have included all the necessary elements, but I would like to e ...

How to efficiently trigger service functions in Angular2 with @ngrx/store/effects?

Currently, I am working on developing an Angular 2 application using @ngrx/store and @ngrx/effects. However, I am facing challenges in determining the appropriate placement of logic outside of actions/effects and when to invoke service functions. For inst ...

Encountering a CSP error during the process of single sign-on using Azure AD with MSAL in an Angular application

I'm currently working on implementing SSO functionality using Azure AD with MSAL in my Angular application. Unfortunately, I've encountered the following error: polyfills.9c9523e6b18dcf83.js:1 Refused to connect to 'https://login.microsofton ...

Tips for utilizing the @Input() property of a component to set the initial value of an input field

Is there a way to utilize the value of an @Input() property on Component B as the initial value for an input field in that component when it is contained within Component A? I attempted passing the value during form construction, but found that it only wo ...

Troubleshooting EasyTabs: Localhost Issue with Ajax Tab Configurations

I've implemented EasyTabs for organizing my tabs on a webpage. I decided to use ajax-tabs functionality in order to fetch content from other pages when users click on the navigation menu buttons. However, I've encountered an issue where the conte ...

Using .htaccess with Angular is specifically designed to function within a subfolder of

After deploying my app on a Debian 11 Apache server within the folder var/www/html (specifically in var/www/html/foo), I encountered issues with routing and hard refreshing, resulting in a 404 error whenever I attempted to refresh a page. The Angular app c ...

Applying REGEX on input text in React Native

I'm having trouble getting my regex function to work correctly, so I believe there might be an error in my code. Any assistance would be greatly appreciated. Here is the regex function I am using: let validatePlate = (plate) => { var re = /(^[A ...

Step-by-step guide to creating a dropdown menu within a form element, with a variety of selectable values generated in

I am dealing with an array of employees who are assigned tests by a Lead. When tests are being assigned, the selected employee is allocated correctly. Upon review, the Lead can easily see which test is assigned to each employee. However, when the table is ...

Having difficulty grasping the reason for the databinding issue in Angular 6

Hey there, I'm relatively new to working with Angular 6 and currently in the process of building my own website using Angular+NodeJs. The interface I'm creating consists of 2 sections each containing 3 buttons. When a button is clicked, it trig ...

Using JSDoc with "T extending Component"

get_matching_components<T extends Component>(component_type_to_return: { new (doodad: Doodad): T }): T[] { return this.components.filter(component => component instanceof component_type_to_return) } In TypeScript, I created a method to retrie ...

Leveraging TypeScript unions within functions to handle and throw errors

As a newcomer to TypeScript, I've encountered an odd error that I need help with. I have various objects sending data to the server and receiving fresh data back of the same object type. These objects use a shared method for sending the data, so I ap ...

Using the .ts extension, transpile TypeScript code for Node.js import

I have a specific file that I plan to utilize the .js file generated in node: import { someFunction } from './otherfile.ts'; How can I compile this? The tsc command is not effective since my tsconfig.json looks like this: { "compilerOptio ...