Execute child function in Angular after parent completes operations on observables within a forEach loop

Within the parent component, I am collecting responses from observables in an array that is then passed to the child component.

parent.component.ts

let categoriesArray = [];

for (let category of listing.categories) {
      this._projectService.getCategories().subscribe((data) => {
             this.categoriesArray.push(data);
       });
}

parent.component.html

<child-comp #childComp [categories]="categoriesArray"></child-comp>

When it comes to the child component, my goal is to trigger a specific function once the for loop with observables in the parent component has completed.

child.component.ts

@Input() public categories;

public limitCategories() {
**//This function should be called by the parent component after all observable calls are done**
...
}

child.component.html

<div class="Category" *ngFor="let item of categories">
...
</div>

I attempted making the categoriesArray an Observable and subscribing to it within the child component, but this would call limitCategories() each time there was a change. My intention is to trigger it only once after the last service call.

Answer №1

If you're looking to access a child component using the @ViewChild decorator, follow these steps:

parent.component.ts

@ViewChild('childComp', {read: ChildComponent})
childComp: ChildComponent;

Inside a loop, you can then call the limitCategories() method:

for (let category of listing.categories) {
  this._projectService.getCategories().subscribe((data) => {
         this.categoriesArr.push(data);
         this.childComp.limitCategories();
   });
}

UPDATE

If you need to wait for all async operations in the loop to finish before triggering limitCategories(), consider using async/await:

parent.component.ts

ngOnInit(){
  this.getCategories();
}

getCategories = async () => {
    for (let category of listing.categories) {
       await this._projectService.getCategories().toPromise().then((data) => 
       {
           this.categoriesArr.push(data);
       });
    }
    this.childComp.limitCategories();
}

Answer №2

Implement the usage of forkJoin operator:

const calls$ = listing
  .categories
  .map(category => this._projectService.getCategories(category))

forkJoin(calls$).subscribe(data => {
  this.categoriesArr = [...data];
  this.childComp.limitCategories();
})

Upon completion of all HTTP calls, forkJoin will execute the child method.

This may not be the optimal solution for your specific case, but it should work sufficiently.

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

Modify the state of a Babylon JS instance that was set up within an Angular 2 component

Hi there, I'm currently experimenting with injecting variables using Angular 2's Dependency Injection to alter the state of an object initialized within BabylonJS. I've tried using [(ngModel)]="Service.var" to access the variable and (ngMod ...

Utilizing string literals as index signatures

I've created a code snippet called MyTest that maps over an object: type MyTest<T> = { [P in keyof T]: T[P]; }; type Result = MyTest<{hello: 'world', foo: 2}>; // ^? type Result = { hello: 'world', foo: 2 } ...

Downloading files using C# .NET Core WEB-API "proxy" functionality

I am utilizing an angular frontend with a PDF viewer along with a C# .NET core API. The .NET core API is responsible for downloading a file from an internal API and then passing it on to the angular PDF viewer as a proxy. While this setup works, the drawb ...

Definitions for TypeScript related to the restivus.d.ts file

If you're looking for the TypeScript definition I mentioned, you can find it here. I've been working with a Meteor package called restivus. When using it, you simply instantiate the constructor like this: var Api = new Restivus({ useDefaultA ...

Is it possible to specify the timing for executing Typescript decorators?

One issue I've encountered is that when I define a parameterized decorator for a method, the decorator runs before the method itself. Ideally, I'd like the decorator to run after the method has been called. function fooDecorator(value: boolean) ...

Obtain a union type using the `keyof typeof` syntax

Is there a way to retrieve the union or enum type from a typeof type in TypeScript? For instance: const myConfs: { [k: string]: (myArg: { name: string }) => string } = { 'Hello': ({ name }) => `World from ${name}`, 'Goodbye': ...

Updating the value of an input field in Angular 2

When I enter 123 in my input field and submit, I want to see 456. Is there a way to change the value of an input programmatically? Here is my HTML code using Ionic2: <ion-textarea [ngFormControl]="message"></ion-textarea> This is the JavaSc ...

Update all occurrences of a particular value to null within the Realtime Database using Firebase Cloud Functions

I need to update the values of a specific userID linked to multiple post keys in my database by setting the userID to null. The userIDs are associated with post keys located in the path: posts/ivies/userIDs in my database. Take a look at how the database i ...

What are the steps to create a circular progress bar in an Ionic 3 application?

Can anyone help me create a circular progress bar in Ionic 3? I'm new to Ionic and have already attempted to install the jQuery circle progress package by running npm install jquery-circle-progress. The installation was successful, but now I'm un ...

Clearly defining the data types for static dictionary values, while also deducing the precise structure or at least the keys

My goal is to create a static dictionary that is defined as a single object literal. I want to: Specify the type of values explicitly for typechecks and IDE suggestions Still have the ability to infer the exact shape, or at least keys I can achieve the f ...

What allows us to create an instance of a generic class even without defining the generic type parameter?

It is intriguing how TypeScript allows the instantiation of a generic class without specifying the actual generic type parameter. For instance, in the code snippet below, the class Foo includes a generic type parameter T. However, when creating a new Foo i ...

Contrasting covariant and contravariant positions within Typescript

I'm currently diving into the examples provided in the Typescript advanced types handbook to broaden my understanding. According to the explanation: The next example showcases how having multiple potential values for the same type variable in co-var ...

The attribute cannot be found within the string or object typescript

Encountering the error: Property 'p' does not exist on type 'string | { p: string; }'. Can someone assist me in resolving this issue? interface x{ n:string | {p:string} } function text(args:x){ const {n:{p}}=args; console.l ...

Having difficulty storing duplicate requests that are crucial for various services/components

Currently, I am tackling a project that involves displaying multiple sets of data to the user. Each set requires several requests to be made to the backend. Specifically, for the UserDetails dataset, I must query the getUser and getSigns endpoints. However ...

Storing data from a popover form in ng-bootstrap for Angular 2+

Is there a way to include an input field in a popover and retain the entered values? When I click the popover button and enter text into the input field, the text disappears when the popover is closed If this is not achievable with ng-bootstrap, could it ...

Combining React with Typescript allows for deep merging of nested defaultProps

As I work on a React and Typescript component, I find myself needing to set default props that include nested data objects. Below is a simplified version of the component in question: type Props = { someProp: string, user: { blocked: boole ...

"Stylish form field design with outlined borders that displays a subtle hover

I am attempting to modify the background color of a mat-form-field outlined when hovering with the mouse. .mat-form-field.mat-form-field-appearance-outline.mat-form-field-outline-thick { // HOVER EFFECT background-color: $dark-blue-200; } The above ...

Ways to stop dialog from disappearing in Reactjs

This code snippet demonstrates the implementation of a popup with buttons, where clicking the cancel button triggers a confirmation dialog. To make the popup disappear when clicked outside of it, the following event handling is employed: const popupRef = ...

Contact the help desk and receive information that is currently unknown

There are a few issues that I'm struggling to resolve. I am utilizing SwaggerService to fetch data, but the response is coming back as undefined. import {SwaggerService} from '../../services/swagger.service'; export class TestComponent im ...

Creating a generic component map resolver for flexible applications

Currently, I am engaged in a project where the backend allows for the modeling of dynamic content that is later displayed as Components on the frontend. Everything seems to be functioning well, except when dealing with models where the dynamic content con ...