Ways to send information from a child component to its parent component when a button is clicked in the

Being new to Angular, I am faced with a challenge of organizing a large form into smaller modular components. I have created multiple child components and integrated their selectors in the main parent component. In the parent component, there is a 'save' button that, when clicked, should send all the data from the form (child components) for an API call.

I am familiar with emitting data from child to parent using '@Output', but I usually trigger this action by clicking a button within the child component. However, in my scenario, there are no buttons within the child components. So I am looking for a more efficient way to achieve the same result. Does anyone have a working example on StackBlitz or any other suggestions?

Any help would be greatly appreciated! Thank you!

Answer №1

When passing an object as @Input (a variable whose value is an object, not a string or number), you don't need to worry about using @Output. If you do need to access the values of the children components, you can use a template reference. For example:

<child-one #childOne ...></child-one>
<child-two #childTwo ...></child-two>
<child-three #childThree ...></child-three>
<button (click)="submit(childOne, childTwo, childThree)">submit</button>

submit(childOne: any, childTwo: any, childThree: any){
   //if, for example, there are variables 'data' in each child component, you can combine them like this:
   this.data = { dataOne: childOne.data, dataTwo: childTwo.data, dataThree: childThree.data }
   //remember that you can access all public variables in the children components as childOne.variable_name
}

Feel free to share other configurations and provide more information :)

Answer №2

If you want the parent component to handle button clicks and communicate with a child component, follow these steps:

  1. In the child component, create an @Input property to receive button click status from the parent:

    Child.ts:

    import { Component, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
    
    @Component({
      selector: 'app-child',
      templateUrl: './child.component.html',
      styleUrls: ['./child.component.css']
    })
    export class ChildComponent implements OnChanges {
      @Input() isButtonClicked!: boolean;
      list: string[] = ['apple', 'orange', 'banana'];
      @Output() onParentButtonClick = new EventEmitter<string[]>();
    
      ngOnChanges(changes: SimpleChanges): void {
        if (changes['isButtonClicked']) {
          if (this.isButtonClicked) {
            this.sendList();
          }
        }
      }
    
      sendList() {
        this.onParentButtonClick.emit(this.list);
      }
    }
    
  2. In the parent component, set up a boolean flag to track button click status:

    Parent.ts:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
      styleUrls: ['./parent.component.css']
    })
    export class ParentComponent {
      isButtonClicked: boolean = false;
    
      submit() {
        this.isButtonClicked = true;
      }
    
      receiveList(list: string[]) {
        console.log(list);
      }
    }
    
  3. Bind the boolean flag to the child component and handle events emitted by the child:

    Parent.html:

    <button (click)="submit()">Click me</button>
    <app-child 
      [isButtonClicked]="isButtonClicked" 
      (onParentButtonClick)="receiveList($event)">
    </app-child>
    

This setup allows the parent to detect button clicks, trigger actions in the child component, and retrieve data for handling. If you need to refresh data on each button click, remember to set the isButtonClicked flag to false before clicking again.

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

"Implementing an Angular route component that adjusts based on specific

I am currently working on routing within my application for the 'feed' module. Within this feed, there are two types of posts that I need to display with a direct link to show full information. How can I ensure that the right component is opened ...

Populate the dropdown menu with data from a JSON file

Recently, I created a custom JSON file and wanted to populate a select>option using this data. However, I encountered an error message saying: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/.../p ...

Vue component fails to react to updates from Vuex

Currently, I am developing a system to facilitate the management of orders at a shipping station. Although I have successfully implemented the initial changes and most of the functionality, I am encountering an issue where one component fails to update ano ...

Scroll bar malfunction in Highcharts

I am struggling to get the scroll bar working so that all categories can be displayed. I have tried different approaches but haven't been able to figure out where I'm going wrong. See the code in action here: http://jsfiddle.net/manraj/7racxxu0/ ...

Guide on utilizing direction.set within threejs for Vector3 types

In the code below, I have defined a plane, wall, and a character. Now, I am trying to set the direction using vector3(). However, I seem to be encountering an issue. Whenever I press the left or right arrow key on the keyboard, I keep receiving the follow ...

Creating a Dual Y-Axis Chart with Two Sets of Data in chart.js

I utilized the chart.js library to write the following code snippet that generated the output shown below. My primary concern is how to effectively manage the labels on the horizontal axis in this scenario. CODE <!DOCTYPE html> <html lang="en"& ...

Enhancing 2D video viewing with Threejs interactivity

I want to create an interactive 2D video using three.js and maintain the aspect ratio of the video when resizing the browser window. Here is the code I am currently using: var camera, scene, renderer; var texture_placeholder, distance = 500; init() ...

What is the best way to display the information from a different React component in the console upon clicking a button?

Below is the code for a button in one of my component files that triggers a form modal: <Button onClick={() => setOpen(true)} style={{ cursor: "pointer", }}> REQUEST </Button> <FormDialog isO ...

React checkbox is experiencing an issue where the onchange event is returning as undefined the first time it is triggered

When using a React checkbox, the onChange event outputs undefined for the first click, and then shows a valid true or false output. I have tried searching online for a solution but have not been able to solve the problem. Can someone please help me identi ...

View pictures on Angular without an internet connection

As I work on an Angular application, I am faced with a challenge in the app.component.ts file. The application should detect when a user loses internet connection while on a certain page, and in response I want to display a component featuring an error mes ...

The requested resource does not have the 'Access-Control-Allow-Origin' header

Currently, I am working on an application that utilizes Angular for the client side and NodeJs for the backend. The application is being hosted with iis and iisnode. Recently, I implemented windows authentication to the application in order to track which ...

Using RXJS within the pipe operator to make numerous HTTP requests

In my project, I have set up 3 API endpoints - candidates, vacancies, and interviews. { "candidates": [ { "id": 1, "name": "Serj" }, { "id": 2, "name": "Alex" } ], " ...

What is the best way to conceal all lists except for the one that has been chosen?

Looking to enhance my sortable list with jQuery UI - currently it's functional, but I'd like to incorporate a dropdown menu for each item to designate the active one when clicked. Is there a way to modify the code so that upon selection, only th ...

What is the best way to combine two functions for the "value" attribute in a TextField?

How can I make a TextField force all uppercase letters for the user when they type, while also storing the text inputted by the user? I have managed to make the TextField display all uppercase letters, but then I can't submit to Excel. On the other ha ...

What is the best way to send multiple arrays of JSON objects to a Stimulsoft report using JavaScript?

I am currently working with this JavaScript code snippet: var viewer = new window.Stimulsoft.Viewer.StiViewer( null, "StiViewer", false ); var report = new window.Stimulsoft.Report.StiReport(); const { data: reportData } = await GetRequest ...

How to retrieve and modify JSON data in Node.js using Stream with both Get and Post methods

Exploring Node.js for the first time, I'm currently tackling a project where I aim to utilize Request for streaming data from one endpoint to another. The objective is to leverage Request for extracting and posting an altered JSON body through a pipe ...

Switch up the image source with Javascript in a random sequence

Looking to create a script that randomly changes the image source of an element with one specified in an array. However, the variable "target" keeps returning undefined. Can you help? HTML <ul> <li><img src="http://www.placehold.it/20x ...

Waiting for the HTTP Post response in Angular 2

My Angular2 app is written in TypeScript. I encounter an issue when making a HTTP Post request to create a new record, as the return value from the service does not come back in time to update the DOM with the newly created record. Is there a way to pause ...

Server-Side Rendering will occur exclusively for the `/` url, but only upon reloading the landing page. This setup utilizes Angular 16, implements Lazy Loading, and runs

Whenever I run my Angular ionic application locally and refresh the pages (all of them), I notice these console logs popping up on my screen. However, once I deploy it on PM2 in a production environment, the console log only shows up for the home page. I ...

Understanding how jQuery ready function works is essential in ensuring proper

My question is regarding an object I have created: function myObj (){ this.name = "noName"; } myObj.prototype = { init: function(){ console.log(this); this.setName(); }, setName: function(){ this.name = "object name"; } } var ob ...