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

Creating synchronous behavior using promises in Javascript

Currently, I am working with Ionic2/Typescript and facing an issue regarding synchronization of two Promises. I need both Promises to complete before proceeding further in a synchronous manner. To achieve this, I have placed the calls to these functions in ...

Displaying related objects information from a single object in AngularFire2 can be achieved by following these steps

As a newcomer to Angular and Firebase, I apologize if my question seems basic. I'm seeking guidance on how to display related object information from one object in angularfire2. Specifically, I want to show the role names assigned to a user. Here is ...

My JavaScript code is not triggering during the page load. Could this be related to .net

I've been attempting to trigger a JavaScript function upon the refresh of an update panel, but for some reason it's not working. Oddly enough, I'm using the same approach that has worked for other functions. In C#, this is what I have in th ...

Convert data in JavaScript and send it as a string in PHP

I'm currently facing a small issue with my JavaScript code. Specifically, I am using AJAX and attempting to retrieve a variable in PHP. Everything seems to be working fine except for the "param" data. Below is the snippet of my code: $('#sign ...

The functionality of `config.assets.debug = true` fails to

I've encountered an issue with the configuration on development where config.assets.debug = true doesn't seem to work correctly. Instead of having multiple separate JavaScript and CSS file inclusions, I'm getting a consolidated one: <li ...

Can someone point me in the direction of the AND and BUT keywords within the cucumber library

After adding the following libraries to my Angular project: "@cucumber/cucumber": "^7.2.1", "@types/chai": "^4.2.16", "protractor-cucumber-framework": "^8.0.2", I noticed that when I open the cuc ...

Leveraging Watchers on props in Vue 3's Script Setup

When passing a prop to a component that declares its state, I am attempting to watch the prop and set the CSS styling accordingly. However, for some reason it is not working as expected. Can anyone help me figure out what might be wrong? <script setup ...

Activate the mat-select selectionChange trigger when making changes to the form via patchValue

I have been working with an angular reactive form that includes a mat-select element with a selectionChange event. After updating the form using patchValue, I noticed that the selectionChange event does not trigger. I'm unsure how to proceed and woul ...

What is the best way to generate an empty object that mimics the structure of an object within an array of objects in AngularJS

I am facing a scenario where I have an array of objects structured like this: $scope.users = [ { ID: "1", Name: "Hege", Username: "Pege", Password: "hp", }, { ID: "2", Name: "Peter", User ...

Is there a way to reverse the upside-down text generated by OffscreenCanvas.getContext().fillText()?

When using OffscreenCanvas.getContext().fillText() to generate text and then OffscreenCanvas.transferToImageBitmap() to create a map, I noticed that the text appeared flipped upside down when applied as a texture in a threejs project. The image clearly sho ...

Organizing a vast TypeScript project: Comparing Modules and Namespaces

As someone relatively new to TypeScript, I am currently working on a small prototyping framework for WebGl. During my project refactoring, I encountered challenges in organizing my code, debating between using modules or namespaces as both have their drawb ...

Trouble locating feature module routes in Angular2

Trying to wrap my head around Angular2 routes. Here's the plunker link for reference: This. I'm facing an issue where it can't seem to locate the \heroes or \hero\:id route specified in the heroes-routing-module. Each time the ...

Identifying the color category based on the color code in the props and displaying JSX output

I am in need of a solution to display colors in a table cell. The color codes are stored in mongodb along with their descriptions. I am looking for a library that can determine whether the color code provided is in RGB or hex format, and then render it acc ...

PHP Pagination Made Easy

Currently, I am developing a website focused on HIV prevention information warehousing. Numerous collaborators will be contributing articles using a tinyMCE GUI. The design team is keen on having control over page lengths. They are interested in implement ...

Exploring the functionality of the instanceof operator in Javascript

I'm currently developing a Node.js application and the project structure is as follows: [Project Folder] | |---[plc] | |--- plc.js | |--- scheduler.js | |---[source] | |--- source.js | |---[test] |--- test.js Th ...

"Ensure that all necessary fonts and assets are included in the development of your Vue component

At the moment, I am utilizing vue-cli-service build --target lib --name myLib [entry] to compile Vue into a component library for integration into other projects. Nevertheless, it only produces four files which are: dist/myLib.umd.min.js dist/myLib.umd. ...

Console log is not displaying the JSON output

I am currently working on implementing a notification button feature for inactive articles on my blog. I want to ensure that the admin does not have to reload the page to see any new submitted inactive articles. To achieve this, I am looking to use Ajax, a ...

Best Method for Confirming Deletion in Data Table with Shadow and UI

I have a query regarding the Shadcn/UI - Data Table component. In my case, I am working with a list of users where each row has a delete button in the last column. Upon clicking the delete button, a confirmation dialog pops up. Currently, I am implementi ...

Issue: The input must either be a single String containing 12 bytes or a string consisting of 24 hexadecimal characters. This problem appears in the context of MongoDB and node.js

Please add the description hereI am attempting to make a get request for each individual blog when they are clicked, however I am encountering an error. Below is the code snippet in question. <% blogs.forEach(blog => { %> <a href="/blo ...

"Implementing a feature in Angular to automatically include a blank mat-option in all non-required mat-select elements

Is there a way to dynamically add an empty mat-option to all not required mat-select elements in my application? For example: <mat-form-field appearance="outline"> <mat-label>HMO</mat-label> <mat-select> ...