A method to simultaneously retrieve all emitted values from multiple EventEmitters in Angular 7

I am facing a scenario where I have a parent component that consists of multiple child components. Each child component may differ from the others, creating a diverse structure within the parent component. Here's an example:

                          --- Parent ---
                                |
 Child1(component1) --- Child2(component1) --- Child3(component5) .....

My goal is to be able to retrieve messages simultaneously from all child components when a button in the parent component is clicked. While I can successfully receive values from individual child components using EventEmitter, I am uncertain about how to gather information from all child components at once.

Edit:

The challenge lies in dynamically creating my child components as shown below:

@ViewChild('component1Container', { read: ViewContainerRef }) component1ContainerRef: ViewContainerRef;
@ViewChild('component2Container', { read: ViewContainerRef }) component2ContainerRed: ViewContainerRef;

Answer №1

In the parent template, you have the option to access your components using their ids:

@Component({selector: 'parent', template: `
  <app-child1 #child1>
  <app-child2 #child2>
  <app-child3 #child3>
  <button (click)="onButtonClick(child1.aProp, child2.anotherProp, child3.thirdProp)"></button>
`})
class ParentComponent {
  onButtonClick(aProp: string, anotherProp: number, thirdProp: string): void { ... }
}

Alternatively, you can utilize the @ViewChild directive to directly access child components from within the parent component:

@Component({selector: 'parent', template: `
  <app-child1 #child1>
  <app-child2 #child2>
  <app-child3 #child3>
  <button (click)="onButtonClick()"
`})
class ParentComponent {
  @ViewChild("child1", {static: false}) child1!: Child1Component;
  @ViewChild("child2", {static: false}) child2!: Child2Component;
  @ViewChild("child3", {static: false}) child3!: Child3Component;

  onButtonClick(): void {
   console.log(this.child1.aProp, this.child2.anotherProp, this.child3.thirdProp);
  }
}

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

Error Message: The Reference.update operation in Angular Firebase failed due to the presence of undefined value in the 'users.UID.email' property

Having recently started to use the Firebase database, I encountered an issue while trying to update the UID to the Realtime Database during signup. The error message displayed was: Error: Reference.update failed: First argument contains undefined in prop ...

Angular 8 httpClient experiencing asynchronous execution issues

I'm currently facing an issue where the order of execution within my WebService.webCall method seems to be incorrect. I am attempting to load content from files in an assets folder using Angular's HttpClientModule. Despite creating a stackblitz c ...

What is the process for setting a default checkbox as checked in Angular 6?

example.component.html <form method="post" enctype="multipart/form-data> <mat-checkbox class="style" name="checkboxenabled"[(ngModel)]="checkboxObj.checkboxenabled">Enabled</mat-checkbox> </form> I have been trying to set the c ...

AngularJS - Sending event to a specific controller

I am facing an issue with my page where a list of Leads each have specific actions that are represented by forms. These forms can be displayed multiple times on the same page. Each form has its own scope and controller instance. After submitting a form, an ...

Error: Unable to access $rootScope in the http interceptor response function

I have set up an interceptor to display an ajax spinner while loading. interface IInterceptorScope extends angular.IRootScopeService { loading: number; } export class Interceptor { public static Factory($q: angular.IQService, $ro ...

Using an array of objects as a data source for the Material Angular table

My user data is causing some issues and looks like this... [{"firstName":"Pinkie","lastName":"Connelly","username":"Darlene.Marvin","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="19506a767b7c75464b7c77777c6b5971766d74 ...

What is the method for importing the "numeric" library version "^1.2.6" into an Angular project?

I recently added the package "numeric": "^1.2.6" to my project. In addition, I included the types: "@types/numeric": "^1.2.1" When attempting to import this into my Angular application: import * as numeric from &ap ...

What is the correct way to set up a custom class instance with specific parameters at the top level?

Is it possible to utilize the defineString(), defineInt, ... functions within a top-level custom class constructor? defineString() returns a StringParam object which has a value() method. I am looking to use parameterized configuration to initialize an in ...

Guide on the correct way to develop a Typescript NPM package accompanied by declarations?

It feels like I'm struggling with a simple task that is driving me crazy. I have several TypeScript files with code that I want to export for an npm package. In order to enable auto-imports from npm packages, all function and constant types need to b ...

Upon updating from Angular5 to Angular7, the slice pipe seems to be stuck in an endless loop

Recently, I upgraded my project from angular 5 to angular 7. However, after completing the upgrade, I noticed that the slice pipe was not functioning correctly. It seemed to be causing infinite loops in the angular core files and even resulted in my browse ...

I am having trouble accessing my JSON data via HTTP get request in Angular 2 when using TypeScript

I am working on developing a JSON file configuration that can be accessed via HTTP GET request in order to retrieve the desired value from the config file and pass it to another component. However, whenever I try to return the value, it shows up as undefin ...

Facing Issues with HTTP Headers in Express or Node?

I have developed an Express/NodeJS REST API that includes setting a custom header on the response: router.route("/api/articles") .get(authCheck, function (req, res) { let pagination = req.get('Pagination').split(","); let cur ...

Is there a specific reason why the app.module.ts file is not generated when I initialize a new Angular application?

Each time I attempt to create a fresh Angular app with the ng new "your-app-name" command, the project structure does not include the app.module.ts file and there is no prompt from the Angular CLI regarding whether to add routing. Additionally, in the main ...

Reactive sidenav in action with Angular

Exploring the creation of a reactive component for educational purposes, disregarding project structure =). My directory layout: app.component.html <app-header></app-header> <app-sidenav></app-sidenav> <app-footer></app ...

Issue encountered while generating a fresh migration in TypeORM with NestJs utilizing Typescript

I am currently working on a Node application using TypeScript and I am attempting to create a new migration following the instructions provided by TypeORM. Initially, I installed the CLI, configured my connection options as outlined here. However, when I ...

Setting the Formgroup status to Invalid will only occur if there are errors in multiple fields, not just one

I'm having an issue with my form where setting passportrank as error does not change the formgroup status to Invalid. Additionally, when I navigate to the next section, the inline error message of "You are not eligible" also gets cleared. ngOnInit() ...

Dealing with nullable objects in Typescript: Best practices

Looking for a solution to have a function return an object or null. This is how I am currently addressing it: export interface MyObject { id: string } function test(id) : MyObject | null { if (!id) { return null; } return { ...

Tips for preserving images while browsing a website built with Angular single-page application

Utilizing Angular's router for component navigation has been beneficial, but I am facing an issue with component reloads when going back. To address the problem of content reloading from the server, I have implemented a solution where the content arra ...

Beware of the 'grid zero width' alert that may appear when utilizing ag-Grid's sizeColumnsToFit() function on multiple ag-Grids that are shown within a tab menu

Encountering a warning message when resizing ag-Grid and switching between tabs. The warning reads: ag-Grid: tried to call sizeColumnsToFit() but the grid is coming back with zero width, maybe the grid is not visible yet on the screen? A demo of this ...

Encountering an issue when using the Google authentication provider with Next.js version 13

I am currently working on integrating next-auth with the Google provider and Prisma in my Next.js application, but I encountered the following error: Error: Detected default export in '/MyProject/foodbrain/app/api/auth/[...nextauth]/route.ts'. Pl ...