The @output decorator in Angular5 enables communication between child and

Hello fellow learners, I am currently diving into the world of Angular and recently stumbled upon the @output decorators in angular. Despite my best efforts to research the topic, I find myself struggling to fully grasp this concept.

Here's a snippet of code to illustrate:

app.component.html:

<app-tutorials(event)="doSomething($event)"></app-tutorials>

app.component.ts:

import { Component} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  doSomething(event){
    alert("This function is being executed");
  }
}

tutorial.component.html:

<button (click)="beingClicked($event)"_>click me</button>

tutorial.component.ts:

import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-tutorials',
  templateUrl: './tutorials.component.html',
  styleUrls: ['./tutorials.component.css']
})
export class TutorialsComponent{

  @Output() event = new EventEmitter();

  beingClicked(event){
    this.event.emit(event);
  }
}

After some reflection, here is my current understanding regarding this topic:

  • The @output decorator serves the purpose of transferring data from child components to parent components exclusively.
  • Upon clicking the button, the function beingClicked(event) is triggered and transmits event information via the $event argument.
  • We are able to emit the event using this.event.emit(event); because we have previously instantiated the event within the class with the statement:
    @Output() event = new EventEmitter();
  • Subsequently, the parent component awaits the (event) in the app.component.html:
    <app-tutorials(event)="doSomething($event)"></app-tutorials>
  • When the event is emitted from the child component, the function doSomething($event) is activated and receives the $event as input.

Question Time:

  1. Could someone kindly confirm whether my understanding is accurate?
  2. Furthermore, what exactly does this EventEmitter accomplish and is it always necessary for data transmission upwards?

Answer №1

Am I understanding this correctly?

You are on the right track with your current understanding. While there are various ways to share data among components, notifying the parent component of an event that needs attention is considered the most suitable approach. To explore more examples and information on component interaction, refer to the documentation available at Parent listens for child event.

Can you explain what the EventEmitter does and if it is always necessary to send data upwards?

The EventEmitter serves as a way for other parts of the code (components, services, etc.) to subscribe to events. The owner of the EventEmitter can then trigger the event with relevant data when needed. Subscribed code can then determine how to handle the event or choose to ignore it if not needed. For further insights, you can also look into Event-driven Programming.

Note that the EventEmitter isn't limited to sending data only upwards (from child to parent). It can also facilitate horizontal communication between child components through a shared service dependency, or downstream communication where child components decide how to respond to events triggered by a parent component using a shared service.

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

Executing multiple server-side methods on an AJAX call in ASP.NET MVC: A comprehensive guide

I am facing a situation where I have a method that is called by jQuery, and its result is displayed on a popup. Sometimes, it takes some time to complete and a blank popup appears with processing message. When clicking on close, the popup disappears but th ...

Ways to verify the occurrence of a successful event following the execution of a save() operation on a model

Below is the snippet of code I am using to store extra properties in a model (specifically, the answer model) selectMedia: => # Post media to server @options.answer.id = @options.answer.get('_id') @options.answer.url = "/v1/answers/#{@o ...

Show the text from the chosen option using jQuery with a button

Hey everyone, I have a question regarding a coding issue I'm facing. In this problem, I am unable to display the text from the selected option when I click the order button. The desired result is to show the selected option that I choose and display i ...

The value of the checkbox model in AngularJS is not defined

I'm encountering an issue where I am trying to send the value of a checkbox from my model to the server. Since the checkbox has not been interacted with on the form, Angular does not assign it a value and returns undefined when I request the value. B ...

Angular - Using the 'name' attribute with the 'mat-select' element

Currently, I am working on an Angular form that involves the dynamic nature of the userEntitiesRoles array. To ensure smooth functionality, each mat-select tag within the ngFor loop requires a unique name attribute. In order to achieve this, I attempted to ...

Utilize JSON data to dynamically populate TextFields or Select menus depending on a specific key in the JSON object

As I retrieve multiple JSON groups from an API, each group contains one or more questions objects. The task at hand is to attach each question along with its corresponding response to a textField. Based on the value of QuestionType, it will be decided whet ...

Attempting to dynamically update the image source from an array when a click event occurs in a React component

Has anyone successfully implemented a function in react.js to change the image source based on the direction of an arrow click? For instance, I have an array set up where clicking the right arrow should move to the next image and clicking the left arrow s ...

What happens to PHP echos when you send a post request to a web page?

I have a question that may seem silly to some. As someone who is relatively new to PHP, I am attempting to view echo statements from a page that I am posting to but not actually navigating to. Directly accessing the page's URL without the necessary po ...

Issue with Lazy Loading in Angular 4 Universal

I recently created a new Angular CLI project to delve into server-side rendering with Angular Universal. Everything was set up and running smoothly, until I decided to implement lazy-loading for a module named 'lazy'. After implementing lazy-lo ...

Navigate to the adjacent IDs

I have multiple sections with varying content and links (previous and next) to navigate to the next section. Initially, everything functions properly. However, when adding a new section in between existing ones, I am required to update all the ids to ensu ...

Utilizing CSS to set a map as the background or projecting an equirectangular map in the backdrop

How can I set an equirectangular projection like the one in this example http://bl.ocks.org/mbostock/3757119 as a background for only the chart above the X-axis? Alternatively, is it possible to use an image of a map as a CSS background instead? .grid . ...

What is the correct way to promise-ify a request?

The enchanting power of Bluebird promises meets the chaotic nature of request, a function masquerading as an object with methods. In this straightforward scenario, I find myself with a request instance equipped with cookies via a cookie jar (bypassing req ...

Tips on retrieving Bootstrap selectpicker value by using loops in Jquery

I am attempting to perform a basic validation using jQuery, where I need to iterate through all elements to check for the existence of values. The validation script is working well except for the jQuery selectpicker functionality. Here's what I have t ...

Error in Material UI when using the select component

CustomComponent.js:98 UI Error: The value undefined provided for the selection is out of range. Please make sure to select a value that matches one of the available options or ''. The available options are: `All`, `Software Development`, `Qualit ...

Error encountered with default theme styling in Material-UI React TypeScript components

Currently, I am working on integrating Material-UI (v4.4.3) with a React (v16.9.2) TypeScript (v3.6.3) website. Following the example of the AppBar component from https://material-ui.com/components/app-bar/ and the TypeScript Guide https://material-ui.com/ ...

Passing a list of objects containing lists in MVC3

Is it possible for me to send an array of objects, each containing arrays, from JavaScript to a MVC action result method? Essentially, I have a KeyValuePair with keys as arrays of strings and I need to return a list of these KeyValuePairs. In my code, I ha ...

Differences in React projects utilizing materialize-css compared to those using react-toolbox or material-ui

Is there a difference in technical benefits or code reliability when directly using material-css in JSX versus utilizing JSX specific libraries like material-ui or react-toolbox? Conversely, could using JSX libraries like material-ui or react-toolbox provi ...

Rule of authentication using Firebase Database

I need to establish a rule in my Firebase Database to prevent unauthorized access for reading and writing purposes. Within my database, there is a collection of words, each containing a "uid" field that corresponds with the uid of the authUser key stored ...

Converting an Array of Objects into a single Object in React: A Tutorial

AccessData fetching information from the database using graphql { id: '', name: '', regions: [ { id: '', name: '', districts: [ { id: '', ...

Developing with Ionic 2 allows you to efficiently run a background service using Cordova

I am currently using Ionic 2 and I have a requirement for my app to perform certain tasks even when it is closed, similar to how Gmail continues to provide notifications all the time. After some research, I came across this documentation: https://ionicfr ...