Transferring information among components and incorporating the ngDoCheck function

We are currently working on transferring data from one component to another using the following method. If there is no data available, we display an error message; however, if there is data present, we populate it in a select box.

showGlobalError = true;

constructor(
  private psService: ProjectShipmentService, 
  private pdComp: ProjectDetailsComponent
) {
    this.psService.tDate.subscribe(x => this.cachedResults = x);
  }

  ngOnInit() { }

  ngDoCheck() {
    if (this.cachedResults.length > 0 && this.count <= 1) {
        this.showGlobalError = false;
        this.populateArrays();
        this.count++;
      }
  }    

  populateArrays() {
    this.reportingProject = [this.pdComp.rProjectNumber];
    this.projectSalesOrder = this.pdComp.rSalesOrder;
    this.clearFilter();
    //  ........

This is how our HTML structure is set up:

<div *ngIf="showGlobalError">
  <h6>The reporting project doesn't have any Shippable Items</h6>
</div>
<div id="search-block" class="box-shadow-block">
   <span>Reporting Project</span>
   <dx-select-box
     [items]="reportingProject"
     [text]="reportingProject"
     [readOnly]="true"
     >
   </dx-select-box>
</div>

The problem we are encountering is that when the Reporting Project number is selected within the dropdown, it disappears upon selecting and clicking elsewhere on the page. We suspect this behavior might be related to the ngDoCheck(). Any assistance on resolving this issue would be highly appreciated.

Answer №1

To start off, ensure that your showGlobalError variable is set to false and handle the logic within your ngOnInit method.

showGlobalError = false;

Update your view with the following code:

<div *ngIf="showGlobalError">
  <h6>No Shippable Items found in the reporting project</h6>
</div>
<div *ngIf="!showGlobalError" id="search-block" class="box-shadow-block">
   <span>Reporting Project</span>
   <dx-select-box
     [items]="reportingProject"
     [text]="reportingProject"
     [readOnly]="true"
     >
   </dx-select-box>
</div>

Answer №2

Use this snippet of code to retrieve data from a service.

this.psService.tDate.subscribe(x => {this.cachedResults = x},
    (err) => {},
    () => {this.checkForCachedResults()}
);

Additionally, create a function to perform your conditional check instead of using doCheck() as shown below:

checkForCachedResults() {
    if (this.cachedResults.length > 0 && this.count <= 1) {
        this.showGlobalError = false;
        this.populateArrays();
        this.count++;
    }
} 

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

Struggling with ajax: Converting a JavaScript variable to a PHP variable

I'm trying to convert a JavaScript variable into a PHP variable in order to use it in an SQL query, but for some reason it's not working as expected. Here is the HTML code: <select id = "dep_ID" name = "dep_ID" onchange="myFunction()"> A ...

Show or hide a component based on a mouse click in Vue JS

After a prolonged absence from working with Vue JS, I find myself in the process of displaying a list of data with a button for each item. The goal is to conditionally render a component when a button is clicked. I am wondering if there is a recommended a ...

Node.js can be utilized to make multiple API requests simultaneously

I am facing an issue while trying to make multiple external API calls within a for loop. Only one iteration from the for loop is sending back a response. It seems that handling multi-API requests this way is not ideal. Can you suggest a better approach fo ...

Obtaining Browser Console Logs with Python Selenium - TCF API Integration

I am looking to extract Tracking Consent Strings (TC-strings) from websites that have implemented the Tracking Consent Framework for GDPR compliance. In the browser console, I can use the following code snippet: window.__tcfapi('ping', 2, functio ...

Is it better to import and use useState and useEffect, or is it acceptable to utilize React.useState and React.useEffect instead?

When I'm implementing hooks for state, effect, context, etc, this is my usual approach: import React, { useState, useEffect, useContext } from 'react'; However, I recently discovered that the following also works perfectly fine: import Re ...

When performing an arithmetic operation, the right operand must be a data type of 'any', 'number', 'bigint', or an enumeration type

My JavaScript code needs to be converted to TypeScript for proper functionality. categoryAxis.renderer.labels.template.adapter.add("dy", function(dy, target) { if (target.dataItem && target.dataItem.index % 2 === 0) { return dy + 25; } ...

Encircling a particular group of cells with a border

I have completed the component with a table layout. My current challenge is figuring out how to surround a range of selected cells with a border, similar to the first cell in the group shown below: https://i.stack.imgur.com/5Euht.png I attempted using d ...

Update the VueJS application by loading and replacing the existing JSON data with new information

Is there a way to dynamically re-render the entire v-for loop and DOM after fetching and loading new JSON data to replace the current one? I want to be able to click on different options and have the products updated. Vue.use(VueResource); var produ ...

Disable Styling and Override Readonly CSS restrictions

What is the correct approach for customizing material design styling when input fields are disabled? Out of the Box https://i.sstatic.net/CvcAV.png Explore Angular Material Input Examples I managed to achieve my objective using the following CSS, but I ...

Bypass Auth0 HttpInterceptor based on certain conditions

During the transition from Firebase to Auth0, my Angular front-end application authenticates users to either Firebase or Auth0 based on their email address. I am working on configuring the Auth0 AuthHttpInterceptor provided in the Auth0 Angular SDK for SPA ...

Tips for retaining input field content within a BootstrapVue table

Below is a BootstrapVue table I'm working with; https://i.sstatic.net/xu5Et.png The code, courtesy of this response, is showcased below; new Vue({ el: '#app', data() { return { filter: '', items: [ { i ...

Angular Iterate Array Forms

Is there a way to iterate my rows based on user input? For example, if the user enters 2 values, I need to display 2 rows. How can I achieve this using FormArray? setCount(count:any){ console.log(count); this.count = count; this.countArray = Ar ...

Are multiple .then(..) clauses in Javascript promises better than just using one .then(..) clause?

In this particular scenario, I have set up a basic 'toy' node.js server that responds with the following JSON object: { "message" : "hello there" } This response is triggered by making a GET request to "http://localhost:3060/" So, it's reall ...

Implementing real-time time updates using php ajax technology

It's fascinating how websites can update the time dynamically without using ajax requests. I currently have a comment system in place. $('#comment').click(function(){ $.post(url,{ comment : $(this).siblings('textarea.#commen ...

Working with JSON structure using Javascript

I successfully transformed an XML file into a JSON format, but now I need to manipulate the data in order to achieve a specific desired structure. Here is the Original format { "machine": "Hassia2", "actual_product_date": "08/24/2017", "holdi ...

Using Angular - Executing a query only when a URL parameter is present

Can I execute this query only if a URL parameter (paramOne) is present? queryAndSubscribe(){ this._subscription = this._activatedRoute.params.pipe( tap (params => { console.log('params = ', params); }), switchMap ...

What is the best way to retrieve the second to last element in a list

When using Protractor, you have convenient methods like .first() and .last() on the ElementArrayFinder: var elements = element.all(by.css(".myclass")); elements.last(); elements.first(); But what about retrieving the element that comes right before the ...

Adjusting the CSS class name based on the screen size and applying styles to that class only during the "onload" event

The website I am currently developing can be found at . It is built on WordPress using the Avada theme and everything seems to be functioning correctly. The image move up effect on this site is achieved with the following JavaScript: window.onload = funct ...

Using Node.js to convert a file name to a timestamp

I need to change a filename into a timestamp in my Laravel application. let test = "/2020-05-16_11-17-47_UTC_1.jpg" I attempted using split and join to replace the -, but I don't believe it's the most efficient method. The desired output should ...

Challenges when using deep linking to URL with AngularJS ui-router

Recently, I encountered an issue after restructuring the folder organization of my AngularJS application. Although I believe this might be a distraction from the root cause, I moved a section of functionality to its own directory for better organization. A ...