What is the best approach to ensure that the variables within a function of an imported component in Angular 8 reflect their current values instead of their initial values?

Within the constructor of a component, I am declaring a private variable for an imported component. For example:

constructor(private x: Xcomponent){}

Afterwards, I am calling a function, scanx(), that is declared inside Xcomponent.

x.scanx()

Within the scanx() function, there is a variable named ShouldChange whose initial value is null. Prior to calling scanx(), its value is changed by a different function inside Xcomponent to {'some':'something'}. However, when scanx() is called from another component, the value of ShouldChange is null. I have tried to access the values of variables declared and changed in classes (not components) and I retrieve the current values, not the initial ones as it's happening when I try to access the values of imported components.

I am using Visual Studio Code IDE. The language being used is TypeScript.

import { Xcomponent } from '../Xcomponent/xcomponent.component';
import { Globals } from '../globals';

export class parentComponent implements OnInit {
    constructor(private x: Xcomponent, private global: Globals) {
    }

    runThisFunction() {
        x.scanx(global.theVariableRetainsEditedValue); // The variable in the global instance retains the changed values.
    }
}

// Inside the scanx function of Xcomponent
export class Xcomponent implements OnInit {
    ShouldChange = null;

    someotherFunction() {
        this.ShouldChange = {'some': 'somethingelse'}
    }

    ngOnInit() {
this.someotherFunction();
this.confirmTheChange();
    }

    confirmTheChange() {
        if (this.ShouldChange === null) {
            alert("This never happens");
        }
        else {
            alert("THE VALUE WAS INDEED CHANGED");
        }
    }

    scanx(SomeInput) {
        if (this.ShouldChange === null) {
            alert("This Should not happen");
        } else {
            alert("This is not happening. Why?");
        }
    }
}

I expected the value of the variable ShouldChange to not be null since it's changed in ngOninit. But it reflects its initial value when called from an imported instance of the component. However, checking the variable's value from the unimported instance of the component shows that the value has indeed changed as shown in the confirmTheChange() function.

Answer №1

It seems like the issue could be that the function is not returning the new value, resulting in the unchanged value...

To ensure the new value is returned, add return y at the end of the function that modified the y value:

scanx(){
*// code that updates the y value*
return y
}

In the component where you call 'scanx', make sure to assign the returned value to a variable:

runThisFunction() {
 const y = x.scanx(global.theVariableRetainsEditedValue); // The global variable retains the updated value.
*y will now hold the updated value*
}

If the issue persists, consider using observables as a solution. You can create an observable in a service to act as a data intermediary between components, with RxJS BehaviorSubject being a viable option.

Step one - Create a new service with a BehaviorSubject and a method to update the observable value:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class ValueChangerService {
  private initialValue = new BehaviorSubject(0);
  currentValue = this.initialValue.asObservable();

  constructor() { }

  changeValue(value: number) {
    this.initialValue.next(value);
  }
}

Step Two - Inject the service into your components and update the value in one component:

import { Component, OnInit } from '@angular/core';
import { ValueChangerService } from './value-changer.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private valueChanger: ValueChangerService) {
  }

  setValue(value) {
    this.valueChanger.changeValue(value);
  }
}

Step Three - Subscribe to the observable in the other component:

import { Component, OnInit } from '@angular/core';
import { ValueChangerService } from "./value-changer.service";

@Component({
  selector: 'hello',
  template: `
   Hello Component
   the value of y is {{y}}
  `,
  styleUrls: ['./app.component.css']
})
export class HelloComponent implements OnInit {

  y: number;

  constructor(private valueChanger: ValueChangerService) { }
  ngOnInit() {
    this.valueChanger.currentValue.subscribe(value => this.y = value);
  }
}

You can access the complete code here: https://stackblitz.com/edit/angular-gvh6xj

Also, check out by Jeff Delaney!

Answer №2

Click here for a live demonstration

Component X

 import { Component, OnInit } from '@angular/core';
    import {TestService} from "./test.service"

    @Component( {
      selector: 'x-child',
      template: ``,
    })
    export class XchildComponent implements OnInit {

      constructor(private valueChanger: TestService) { 

         this.valueChanger.currentValue.subscribe(value =>  
         this.ShouldChange = value
            )
      }

      ShouldChange = null;

        someotherFunction() {
          //  this.ShouldChange = {'some': 'somethingelse'}

             this.valueChanger.changeValue({'some': 'somethingelse'});
        }

        ngOnInit() {

          this.someotherFunction();
          this.confirmTheChange();
        }

        confirmTheChange() {
            if (this.ShouldChange === null) {
                alert("This scenario will not occur");
            }
            else {
                alert("THE VALUE HAS BEEN SUCCESSFULLY CHANGED");
            }
        }

        scanx(value: any) {
            if (this.ShouldChange === null) {
                alert("This should not be happening");
            } else {
                alert("Why is this not taking place?");
            }
        }
    }

Parent component

import { XchildComponent } from './x-child.component'
import { Component , ViewChild, AfterViewInit} from "@angular/core";

@Component( {
  selector: 'parent',
  template: ``,

})
export class ParentComponent implements AfterViewInit {
constructor(public child: XchildComponent) {

}


ngAfterViewInit() {

this.child.scanx('checking new value')
}


}

Hoping that this solution resolves your issue

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

What is the process for accessing my PayPal Sandbox account?

I'm having trouble logging into my SandBox Account since they updated the menu. The old steps mentioned in this post Can't login to paypal sandbox no longer seem to work. Could someone please provide me with detailed, step-by-step instructions o ...

What is the correct method for service injection in Angular 8?

I have encountered an issue while trying to inject a service into my main "App" component. The error message is shown in the screenshot below: constructor(private newsApi: NewsApiService) {} Upon importing the service using the code above, I received the ...

The error message "core.js:10101 NG0303: Unable to link to 'matCellDefOf' because it is not a recognized property of 'td'" was displayed on the console

While utilizing Mat table from Angular Material, an error appears in the console as shown in this image: core.js:10101 NG0303: Can't bind to 'matCellDefOf' since it isn't a known property of 'td'. View image description here ...

Implementing global user authentication state with Zustand in Next.js version 13.4.9

I'm grappling with incorporating zustand into my Next.js 13.4.9 app, specifically for managing global authentication state. Below is the code snippet I have in my application: zustand store: // /src/store/AuthStore.ts import { create } from 'zu ...

Pressing the tab key while using Angular will halt any additional processes from running

I recently integrated a search bar into my Angular application. When I enter text in the input field, a customized dropdown menu appears below it. However, when I press the tab key, I expect the dropdown to close and for the focus to shift to the next inpu ...

Explore a vast array of items in a collection

I have a massive collection of various objects that I need to sift through. With over 60,000 elements, the search operation can sometimes be painfully slow. One typical object in this array has the following structure: { "title": "title" "company": ...

create parameters for the angular properties of chemical functions

I have two functions that clear cancer and reproductive dropdowns individually. Now, I want to combine these functions into a parametrized function that takes a chemical input: clearDropdown(chemical) { switch (chemical) { case 'cancer& ...

Using the rxjs repeatWhen operator within the http request pipeline to automatically resend the request if the expected response is not received

I am attempting to simplify my HTTP request pipeline by ensuring that if the response does not contain the required data in res.myCondition, I can use repeatWhen to make another call. However, it seems like I am not using repeatWhen correctly (Angular 8/ R ...

Error: Unable to parse string in URI within vscode API

Console LOG displays: \Users\skhan\Library\Application Support\Code\User\summary.txt The loop is used to replace the slashes. It works fine in Windows but not in Ubuntu and Mac. This is an example on OSX 10.11.6. Howev ...

Testing the timeout of Angular Karma tests while evaluating the AppComponent with the CUSTOM_ELEMENTS_SCHEMA

While integrating an app-component test into my Angular project, I encountered a timeout issue when running all the tests: [launcher]: Launching browsers headless with concurrency unlimited 21% building 95/96 modules 1 active .../src/css/public.scss19 [l ...

Unable to locate module 'fs'

Hey there, I'm encountering an issue where the simplest Typescript Node.js setup isn't working for me. The error message I'm getting is TS2307: Cannot find module 'fs'. You can check out the question on Stack Overflow here. I&apos ...

Using Angular in conjunction with a chrome extension that includes a content script

Currently, I am developing a Chrome extension with Angular to handle styling and routing. My issue lies in the communication between content and background scripts - specifically, when I update a variable in component X using chrome.runtime.onMessage, Angu ...

While utilizing Typescript, it is unable to identify changes made to a property by a

Here is a snippet of code I am working with: class A { constructor(private num: number = 1) { } private changeNum() { this.num = Math.random(); } private fn() { if(this.num == 1) { this.changeNum(); if(this.num == 0.5) { ...

Is Angular's forkJoin being phased out?

Upon opening my Angular project today, I came across a warning message that said: The utilization of forkJoin is marked as deprecated: resultSelector is deprecated, it is recommended to use pipe to map instead (deprecation) https://i.sstatic.net/vFpeu.pn ...

Use Advanced Encryption Standard Algorithm (AES) to encrypt text with TypeScript and decrypt it using C# for enhanced security measures

Struggling with implementing encryption in TypeScript and decryption in C#. After searching online, I found some resources related to JavaScript, not TypeScript. Encrypt in JavaScript and decrypt in C# with AES algorithm Encrypt text using CryptoJS libra ...

Combine a constant interface with a generic function to create a unique generic interface

When dealing with legacy code that utilizes a const in the following pattern: const fnUsedInSetPrototypeOf = { equalityComparer<T>(a: T, b: T) { return a === b }, otherFn<T> (this: T) { /*...*/ }, // ... other things, all along the ...

issue with lazy loading Angular module containing a preview component

Greetings everyone! I successfully created an Angular app with lazy loading, but I encountered an issue when trying to open child pages inside modules. Instead of opening within the main page, it redirects me to a new page. Here is my module structure: co ...

Can the NGXS store be shared between independent Angular (sub)projects?

Current Scenario: I am working on a micro-frontend setup consisting of a primary Angular application acting as the host, with multiple Angular libraries imported as modules that function as separate 'sub-apps'. Objective: My main aim is to estab ...

Unexpectedly, optimization causing issues on Angular site without explanation

Currently, I am utilizing Angular to construct a front-end website that searches for and showcases information obtained through API requests. Whenever I compile the project into a file bundle for static deployment using ng build, I notice that the resultin ...

Extending a class with diverse types in Typescript: A guide

I have a class with multiple methods that deal with an entity referred to as "entity." class entity { entityName: string = ''; getList(): any[] { someAPI + this.entityName .... } getOne(): any{ } } Additionally, there are specifi ...