Having trouble retrieving hidden values from a new Angular/JavaScript window

I have created a form inside a component

HTML

<button type="button" (click)="myForm(i)">

TypeScript

  myForm(i) {
   let form = document.createElement('form');
   form.setAttribute('action', this.urlAddr);
   form.setAttribute('id', 'test');
   form.setAttribute('target', this.name);
   let method = this.name === 'query' ? 'GET' : 'POST';
   form.setAttribute('method', method);
   let hiddenField = document.createElement('input');
    hiddenField.setAttribute('type', 'hidden');
    hiddenField.setAttribute('name', 'type');
    hiddenField.setAttribute('value', '1');
    form.appendChild(hiddenField);
    let hiddenFieldTwo = document.createElement('input');
    hiddenFieldTwo.setAttribute('type', 'hidden');
    hiddenFieldTwo.setAttribute('name', 'sas');
    hiddenFieldTwo.setAttribute('value', 'cnt');
    form.appendChild(hiddenFieldTwo);
   let token = document.createElement('input');
   token.setAttribute('id', 'token');
   token.setAttribute('type', 'hidden');
   token.setAttribute('name', 'secureToken');
   token.setAttribute('value', this.securityToken);
   form.appendChild(token);
   document.cookie = 'Flag=Y';
   document.body.appendChild(form);
   form.submit();
}

When I attempted to retrieve the value of 'token' field in the new window's TypeScript file, it returned undefined.

TypeScript for the new window

  ngOnInit() {
    console.log('test'); //this prints but nothing below prints in the new window
    let inputElement: HTMLInputElement = document.getElementById('token') as HTMLInputElement;
    let inputTwoElement: HTMLInputElement = document.getElementsByName('secureToken')[0] as HTMLInputElement;
    if (inputElement) { 
      const token: string = inputElement.value;
      console.log('target token =' + token);
    }
    if (inputTwoElement) {
      const token: string = inputTwoElement.value;
      console.log('target tokenTwo =' + token);
    }
}

I am puzzled as to why I am unable to retrieve any value. The request is a 'GET' request and the value should be accessible from the parent window. What could be missing or done incorrectly?

Answer №1

When all your code resides in the same module, an effective approach is to utilize ViewChild and ElementRef to gain access to the elements as demonstrated below:

import { Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core';

@Component({
    selector: 'app',
    template: `
        <div #myivId>Some text</div>
    `, }) export class AppComponent implements AfterViewInit {
    @ViewChild('myDivId') myDiv: ElementRef;

    ngAfterViewInit() {
        console.log(this.myDiv.nativeElement.innerHTML);
    } }

However, if the codes you've posted are within different elements, they do not share the same DOM access. Each operates within its own document before amalgamation into a Single Page HTML post-build.

On a side note, for data sharing between components, employing a Service is the recommended practice and stands as one of Angular's key strengths.

Various methods can be employed to achieve what you desire, and I suggest exploring this resource for further insight:

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

Adjust the minimum height and width when resizing the window

Apologies in advance if this has already been addressed, but I have tried solutions from other sources without success. My Objective: I aim to set the minimum height and width of a div based on the current dimensions of the document. This should trigger ...

How can I retrieve the name of a constant enum member in TypeScript as a string?

Consider the following const enum declaration: const enum Snack { Apple = 0, Banana = 1, Orange = 2, Other = 3 } Is it possible in TypeScript to retrieve the string representation of a specific member? In C#, this could be achieved with ...

Vue verifies the readiness of two computed properties

Each time I want to determine when multiple computed values are ready, I create another computed property like isFizzAndBuzzReady. computed: { fizz () { return ['f', 'i', 'z', 'z'] // asynchronous data retriev ...

Exploring the functionality of setAttribute method in JavaScript

Snippet: activeCell.onclick = function() { console.log(element); element.value = this.value; console.log(element.value); console.log(element); }; Imagine activeCell as a span with value = "678", while element is represented by a simple in ...

An iframe perfectly centered both horizontally and vertically, featuring a 16:9 aspect ratio and utilizing the maximum screen space without any cropping

Specifications: It is mandatory for the iframe to be enclosed within a div container as shown in the code below. The container should have the flexibility to adjust to any valid width and height using the vw and vh viewport units. Check the code provided ...

Tips for enabling both vertical and horizontal scrolling using the mousewheel on a webpage

Our website features a unique scrolling functionality where it starts off vertically and then switches to horizontal once the user reaches the bottom. This allows for a seamless transition between scrolling directions. In addition, users can easily naviga ...

Can one assign the type of a sibling property to another property within a nested object?

In search of a solution: I am attempting to develop a function, which we'll refer to as test, designed to handle nested objects with dynamic keys on the first level. The goal is for this function to automatically suggest the type of method without req ...

What is the best method to replace the `click` event of an element selected using jQuery?

As I work on my program, I am attempting to alter the click event of a jQuery element. However, rather than modifying it as expected, it seems to be adding a new event each time. $myelem = $('.nav-item'); $myelem.click(function(){ console.lo ...

Arrows on the button are unresponsive and there seems to be an incorrect number of

I've been working on a project by combining various examples I found online. I'm puzzled as to why it's displaying all the buttons at once instead of just one per page, and why the number of visible buttons decreases by one with each right c ...

The initial click may not gather all the information, but the subsequent click will capture all necessary data

Issue with button logging on second click instead of first, skipping object iteration function. I attempted using promises and async await on functions to solve this issue, but without success. // Button Code const btn = document.querySelector("button") ...

Issues with fetching data from a Drupal module using an Ajax call

I have created a custom module in Drupal where the .js file is supposed to make an ajax call to a .module file. However, I am facing issues as the ajax call is not functioning properly. Can someone please assist me with this? Below is my .js file: // Jqu ...

Implementing an ES6 class in a next.js application: A step-by-step guide

Currently, I am in the process of developing a next.js application and am looking to extract the code that interacts with the database from the API. To achieve this, I have developed a class that serves as a manager: class UserManager { async findUser ...

Tips for personalizing and adjusting the color scheme of a menu in ant design

I am currently working on a website using reactJs and ant design. However, I have encountered an issue with changing the color of a menu item when it is selected or hovered over. Here's the current menu: Menu Image I would like to change the white col ...

Scrolling in iOS 8 causing flickering problem with background image

Utilizing the Supersized jQuery slider plugin to create a full-page background slider with a fade-in effect and added height for scrolling. The slider functions correctly on desktop, but upon testing on an iOS 8 iPad device, there is noticeable flickering ...

Unresponsive display on both 'Ionic development application' and 'physical mobile device'

As a newbie to Ionic, I recently delved into the world of Ionic 4 by following the guidance provided in the Ionic 4 documentation. After setting up my project using ionic start myApp sidemenu --type=angular, I noticed that everything ran smoothly on my bro ...

What is the best way to create an arrow that tracks the browser window, but only goes as far as the end of its designated container

Currently, I am facing a challenge in implementing a scroll down arrow. While this is typically a simple task, it has proven to be a bit more complex this time around. The complexity arises from the fact that my customer desires a homepage with an image of ...

The art of slipping away from a character in JavaScript while adding HTML using jQuery

I am trying to add multiple HTML canvas elements to an existing HTML canvas. <div> <canvas id="BackGroundImage" width="800" height="300" style="position: absolute; z-index: 0;"></canvas> <canvas id="canvas" width= ...

When attempting to access "this.state" in the Chrome Sources tab, the result is an undefined value

Exploring the world of React and currently delving into tutorials on "The Net Ninja" YouTube channel for the Complete React Tutorial (& Redux). The focus so far has not touched on debugging in Chrome, leading to a bug where adding a new UI component to ...

"Upon updating, the array within the mapped state to props in React Redux appears to be

As I work on updating a user's profile through a form, my goal is to ensure the component rerenders after the update and displays the correct information on the form once saved. Here is what I have implemented so far: ProfileInput.tsx const ProfileI ...

Build an equilateral triangle with the power of three.js

I'm currently working on creating an equilateral triangle using three.js, but it seems like what I've created is a bit too tall. My vertices are defined as follows: new THREE.Vector3(0, 0, 0), new THREE.Vector3(4, 0, 0), new THREE.Vector3(2, 4, ...