Angular - passing information to a nested component

Within my application, I have a main component along with three sub-components.

I am passing data to these three sub-components and using setTimeout to manage the timing of the data being sent.

The first sub-component displays for 5000 milliseconds.

The second sub-component displays for 10000 milliseconds.

The third sub-component displays for 15000 milliseconds.

Each sub-component contains a spinner that hides once the data has been received by that specific component.

The issue I'm facing is that when the data arrives at the first component, all the spinners in the other components disappear as well.

export class AppComponent {
  public dataOne: string;
  public dataTwo: string;
  public dataThree: string;

  constructor() {
    setTimeout(() => {
      this.dataOne = "one";
    }, 5000);

    setTimeout(() => {
      this.dataTwo = "two";
    }, 10000);

    setTimeout(() => {
      this.dataThree = "three";
    }, 15000);
  }
}

<one [data]="dataOne"></one>
<two [data]="dataTwo"></two>
<three [data]="dataThree"></three>

export class OneComponent implements OnChanges {
  @Input() data: string;

  constructor(private spinner: NgxSpinnerService) {
    this.spinner.show();
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes["data"] && changes["data"].currentValue) {
      this.spinner.hide();
      console.log(changes["data"].currentValue);
    }
  }
}

Check out the code on StackBlitz

Answer №1

To include the NgxSpinnerService in the provider list for every child component, you can add the following code:

providers: [NgxSpinnerService]

Answer №2

The issue lies with the ngxSpinnerService due to its singleton nature. The official documentation states:

To have multiple instances of ngx-spinner, simply include a name attribute with the ngx-spinner component. However, when doing so, you must specify the name of the spinner in the show/hide method.

Best regards

Answer №3

To ensure each component instance has access to a provider, simply include the provider in the providers array within the @Component decorator as shown below:

@Component({
  selector: "one",
  templateUrl: "./one.component.html",
  providers: [NgxSpinnerService] // <---- DON'T FORGET THIS
})
export class OneComponent implements OnChanges {
  @Input() data: string;

  constructor(private spinner: NgxSpinnerService) {
    this.spinner.show();
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes["data"] && changes["data"].currentValue) {
      this.spinner.hide();
      console.log(changes["data"].currentValue);
    }
  }
}

You can view an example implementation here: https://stackblitz.com/edit/angular-1hqv61

Answer №4

An efficient method would be to incorporate a counter; each time there is a change, update the counter. Once the counter reaches 3, it indicates that all 3 child components have successfully received inputs from the parent:

Component({
  selector: "one",
  templateUrl: "./one.component.html",
  providers: [NgxSpinnerService] // <---- ADD THIS
})
export class OneComponent implements OnChanges {
  @Input() data: string;
dataChangeCounter =0;

  constructor(private spinner: NgxSpinnerService) {
    this.spinner.show();
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes["data"] && changes["data"].currentValue) {
dataChangeCounter += 1;
if(dataChangeCounter ===3){
      this.spinner.hide();
}
    }
  }
}

Note that this approach works well for a single input property. If you need to handle multiple input properties, some modifications to the code will be required.

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

Exploring Nested <Routes> with ReactJs

My decision on whether to display the Foo page or the Bar page is based on the route. However, the Foo page itself contains two sub-routes for components to render depending on the URL path - such as FooOne or FooTwo. This results in having two layers of r ...

What is the best way to insert more rows into a mat-table without disrupting the existing layout?

Having trouble adding 2 additional columns (status and buttons) after the ngfor. It seems to be disrupting the entire structure, as shown in the image below: View the Broken Table Screen Shot I am making modifications based on code from material.angular. ...

Issue with unit testing a ViewportRuler in Angular 2 Material Library

I am currently working on an Angular2 component that includes a tab control from @angular/material. During testing of my component (refer to the simplified code below), I encountered the following error: Error: Error in ./MdTabHeader class MdTabHeader - ...

Implementing typing for a module that exports an instance of a particular class

Attempting to create a .d.ts file for the foo-foo-mq module has presented some challenges. Following the documentation, a 'foo-foo-mq' folder was created within the 'typings' directory at the project's root. An index.d.ts file was ...

Automatically forwarding to another page in Angular 4 due to idle time

Is it possible to implement a timeout feature for inactivity on a webpage? For example, if a user is idle for 20 seconds without interacting with the page, can we automatically redirect them to the home screen? I've been struggling to get this functi ...

Utilizing type guards in prop functions for conditional rendering within React TypeScript adds an extra layer

In my code, I am conditionally rendering a Button. However, I encountered an issue on line 7 where TypeScript is indicating that the first parameter of the exportExcel function may be null even though it should not be, considering the conditional render lo ...

What steps do I need to take to resolve the issue with the coa npm library version 2.1

While working on my Angular project, I encountered an error in the console logs: Error: 404 Not Found - coa-2.1.3.tgz I have not listed this library in my package.json file and the latest version available is 2.0.2. I am unsure about what steps to take ...

By constantly subscribing to a Behavior Subject, updating the data, and then resetting the value, an endless loop is created

We have implemented a wizard functionality with lazy loading, consisting of a parent component and multiple child components. const routes: Routes = [ { path : '', component : WizardHomeComponent, canActivate: [HomeGuard], chil ...

The value in reactive forms is represented as an object containing the key "value" with the corresponding value of "therealname", instead of just being the string "therealname"

Snippet Example: <div>name: {{fg.get('name').value | json}}</div> When I set up the reactive form with #1 this code snippet: this.fg = this.fb.group({name: "myname"}); The result in the div is, name: myname #2 However, using e ...

How can I access a service without the need to import its provider module?

My goal is to grasp the concept of multiple NgModules in an angular application and how they interact, specifically focusing on importing a SharedModule for commonly used services into lazily loaded feature modules. Here's the sequence of steps I fol ...

Angular: Activate async validator for form group only when all controls have values

Is there a way to trigger validation for FormGroup only after all the fields in the group have been filled out, instead of triggering it every time a field is filled? ...

Tips for managing the outcome of an HTTP Post request

I am currently working with Angular 2 and Node.js, attempting to incorporate braintree into my project, which has proven to be quite challenging. My current approach involves utilizing an HTTP Post request to send back the result object from the transacti ...

Create a custom data structure resembling a record, where certain keys are assigned specific value types

My objective is to establish a custom type resembling a record, where certain keys are designated for specific value types. The proposed object would look something like this: const o: TRec = { text: "abc", width: 123, height: 456, //...an ...

The 'flatMap' property is not found on the 'string[]' data type. This issue is not related to ES2019

A StackBlitz example that I have set up is failing to compile due to the usage of flatMap. The error message reads: Property 'flatMap' does not exist on type 'string[]'. Do you need to change your target library? Try changing the ' ...

What is the best way to bring in a SCSS file within another SCSS file?

When working with SCSS, I find myself using a lot of variables. To keep things organized, I create a separate file that contains all of my SCSS variables. The next step is to import this file into other SCSS files. Here's what I tried: Create a fil ...

Angular throws a NullInjectorError when a unit test fails due to issues with dependency

As a newcomer to Angular, I am struggling to grasp the concept of Dependency Injection (DI) and how it functions. My current challenge involves trying to pass a unit test successfully. Below is the code for the test; import { TestBed } from '@angula ...

The menu's mouseover event is activated when hovering over the inner element

Whenever a user hovers over a specific element, a menu appears. This menu remains visible only as long as the user is hovering over it. However, the issue arises when there are elements within the menu itself, causing the menu to hide when the user hovers ...

What is causing the loss of data when attempting to access an array field within an object?

So I've been grappling with this issue. I have a collection of objects, each containing string arrays and a string based on the following interface: export interface Subscription { uid: string; books: Array<string>; } The problem arises whe ...

Typescript and Mongoose Schema - Common Design Mistakes

I am encountering two issues while defining a schema using mongoose and typescript. Below is the code snippet I'm having trouble with: import { Document, Schema, Model, model} from "mongoose"; export interface IApplication { id: number; name ...

A guide to turning off tab discarding in Google Chrome with JavaScript

Is there a way to prevent Chrome from discarding tabs on chrome://discards/ using JavaScript so that the tab remains open even after closing the page or browser? I am aware that this can be achieved with an extension, but I am interested in creating my o ...