"Learn how to trigger an event from a component loop up to the main parent in Angular 5

I have created the following code to loop through components and display their children:

parent.component.ts

 tree = [
    {
      id: 1,
      name: 'test 1'
    }, {
      id: 2,
      name: 'test 2',
      children: [
        {
           id: 3,
           name: 'test 3'
        }
      ]
    }
 ]

nodeClicked(event) {
    console.log(event);
}

parent.component.html

<app-child [tree]="tree" (nodeEmitter)="nodeClicked($event)"></app-child>

child.component.ts

@Input() tree;
@Output() nodeEmitter = new EventEmitter();

clickToEmit() {
    this.nodeEmitter.emit(1);
}

child.component.html

<ul>
  <li *ngFor="let node of tree">{{ node.name }}</li>
  <button (click)="clickToEmit()">Click Me!!!</button>
  <app-child [tree]="node.children" (nodeEmitter)="nodeClicked($event)"></app-child>
</ul>

However, I am encountering an issue:

  • I can receive the emitted event in parent.component.html, but

  • I am unable to receive the emitted event from child.component.html back to
    parent.component.html.

An error is appearing indicating that nodeClicked is not defined in child.component.ts.

Can anyone point out what mistake I might be making here? I have spent several hours trying to resolve this problem.

Thank you for any assistance provided. :-)

Answer №1

Ensure that the child component continues to pass the event up to the parent. Adjust your template so that the emitter re-triggers when a child event takes place.

<ul>
  <li *ngFor="let node of tree">{{ node.name }}</li>
  <button (click)="clickToEmit()">Click Me!!!</button>
  <app-child [tree]="node.children" (nodeEmitter)="nodeEmitter.emit($event)"></app-child>
</ul>

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

What is the best way to modify the nested state of a dynamically generated state with the useState hook?

I'm currently facing a challenge when trying to update a nested property of a useState object. Here's the specific scenario: In the component, there is a prop "order" that contains multiple items (line_items) which represent the products in th ...

IONIC 3 [ERROR] There was a problem encountered during the execution of cordova run android, resulting in an exit code of 1

While trying to run the command 'ionic cordova run android' for Ionic 3, I encountered an error that has left me stumped. Here's a snapshot of the error message: This Result Error [13:29:45] preprocess started ... [13:29:45] deeplinks sta ...

What is the best way to organize data subsets in Firebase?

I am currently working on saving data from multiple sections within my webapp. One section involves storing employee information, while the other deals with employer group information. However, when I save this data in Firebase, it all gets organized by ID ...

Enhanced jQuery implementation for hiding elements

I encountered a peculiar issue where jQuery's .is(':hidden') function wrongly returned true for an element that visibly displayed content. You can see the problem demonstrated in this fiddle. The :hidden pseudo checks both offsetWidth and o ...

The CSS class names for Next.js have not been defined yet

Just getting started with next js and trying to use css modules for styling my nav component. However, I noticed that the classname I setup for the nav element is not showing up in the rendered DOM. Even though I can see the generated styles by webpack in ...

What is the best way to send a list of data as either strings or integers through a REST API using Angular's

While trying to post data from Angular formData to a Django REST API, I encountered an error saying "Incorrect type. Expected pk value, received str." Here is how I am currently sending the data using form data: let noticeData = this.announceForm.value; i ...

What are the best plugins and projects to maximize IntelliJ IDEA's potential for JavaScript development?

I am currently in the process of developing a web application utilizing the MEAN stack: MongoDB, Express, Angular, and Node.js. The foundation of my project is built upon Daftmonk's angular-fullstack Yeoman generator. Despite my primary experience be ...

Breaking Down and Optimizing your Code with Destructuring and

Currently, I am performing some basic destructuring in Javascript: //@flow "use strict"; (function(){ const {a,c} = check(true); })(); function check(bool:boolean):{|a:string,c:string|}|{||}{ if(bool){ return { a:"b", c:"d" } ...

Can you provide a tutorial on creating a unique animation using jQuery and intervals to adjust background position?

I am attempting to create a simple animation by shifting the background position (frames) of the image which serves as the background for my div. Utilizing Jquery, I aim to animate this effect. The background image consists of 6 frames, with the first fr ...

Express is throwing a TypeError because it is unable to access the property 'app', which is undefined

On my nodejs server running the express framework, I have been encountering a random error when making requests. The error occurs unpredictably, usually appearing on the first request and not on subsequent ones. It's challenging for me to identify the ...

What is the concept of NonNullable in typescript and how can it be understood

In TypeScript, the concept of NonNullable is defined as type NonNullable<T> = T extends null | undefined ? never : T For instance, type ExampleType = NonNullable<string | number | undefined>; Once evaluated, ExampleType simplifies to type Exa ...

Execute script when on a specific webpage AND navigating away from another specific webpage

I created a CSS code that adds a fade-in effect to the title of my website, and it works perfectly. However, I now want to customize the fade-in and fade-out effect based on the page I am transitioning from. My desired outcome: If I am leaving the "Biolo ...

Restore Bootstrap Dropdown values to their initial settings when clicked

I need a button that can reset all filter dropdown values to their default values. The current code I have only changes all values to "Filter" when reset, but I specifically need it to reset to "Car brand" and "Model". Here's my code: // set.... $(" ...

The Vue.js transition feature seems to be malfunctioning when trying to display a modal

I can't figure out why my animation isn't working with Vue transitions. Here is the code I have: <template> <teleport to="body"> <div class="modal-overlay" v-if="loading"> <transitio ...

Angular elements that function as self-validating form controls

I'm wondering if there's a more efficient approach to achieve this, as I believe there should be. Essentially, I have a component that I want to function as an independent form control. This control will always come with specific validation requi ...

Error encountered while attempting to validate and add new entries

I am facing a challenge while attempting to insert a record into my mongodb database. Despite providing what seems to be the correct values, mongoose is flagging them as missing. Below is the Schema I am working with - var mongoose = require('mongoo ...

Looking for a Hack to Integrate a Music Player into Your Website?

Currently, I am utilizing the Jplayer plugin from JQuery to incorporate an Audio player into my website. I have come across a situation where: If the user is not currently listening to any music while browsing the website, the page can load without any i ...

Troubleshooting Angular2 component testing: Why is Karma not loading the templateUrl?

As I work on writing tests for my Angular2 application, I am encountering a problem. When I use the templateUrl property in the Angular2 component, linking it to an HTML file, instead of using the template property, the test fails to run. The async callbac ...

Demystifying Iron Ajax: Unraveling the process of parsing an array of JSON objects from a successful

When making an AJAX call to the server, I receive a response in the form of an array of objects as JSON. [{"dms":[{"serialNo":"EG0022","status":"running","firmwareStatus":"ok","latitude":37.8688,"longitude":-144.2093,"toolType":1},{"serialNo":"EG0022","st ...

React: A guide to properly utilizing PropTypes inheritance

I've created a wrapper component for React Router Dom and Material UI: import Button from '@material-ui/core/Button'; import React from 'react'; import { Link as RouterLink } from 'react-router-dom'; const forwardedLink ...