Issue with Angular 5 EventEmitter causing child to parent component emission to result in undefined output

I've been trying to pass a string from a child component to its parent component.

Child Component:

//imports... 

    @Component({
    selector: 'child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.css'],
    providers: [ChildService]
    })

export class DataTableComponent implements OnInit {
    constructor(private http: HttpClient, private childService : ChildService) {}

    myMap = new Map<string, ISomeInterface>();
    currentSelection: string;

    @Output() sendDataEvent = new EventEmitter<string>();

    sendData() {
        console.log("sending this data:  " + this.myMap.get(this.currentSelection).name);
        this.sendDataEvent.emit(this.myMap.get(this.currentSelection).name);
    }
}

Parent Component:

html ->

<d-table (sendDataEvent)="receiveBusinessCycle(event)"></d-table>

typescript ->

//imports...

@Component({
  selector: 'parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css'],
  providers: [ParentService]
})
export class MyParentComponent {
  totoName: string;

  constructor(private parentService : ParentService) {  }

  receiveBusinessCycle($event) {
    console.log($event); //shows in console 'undefined'
    console.log($event as string); 
    this.totoName = $event;
  }

}

The problem is that I'm receiving an undefined event when trying to get the data in the parent component, here are the console logs:

sending this data: 201808
main.bundle.js:2328 undefined
main.bundle.js:2329 undefined

Any suggestions on how to solve this issue?

Answer №1

It is important to utilize $event in this scenario:

<d-table (sendDataEvent)="receiveBusinessCycle($event)"></d-table>

I have encountered a similar issue before, and it appears that only $event works because it is a reserved keyword for accessing the event object.

In Angular, the corresponding DOM event object is provided exclusively through $event. This means using any other variable as an argument will not function correctly. Further information can be found here.

Furthermore, Angular discourages passing events in this manner when dealing with native HTML Elements, as it blurs the distinction between template and component responsibilities. Instead, Angular advocates for the use of Template Variables. More details are available here.

Answer №2

Don't forget to include the $ prefix before using the event parameter. The variable $event is a reserved word, so make sure your data is only accessible to the event handler in the component markup with the specified name $event.

<d-table (sendDataEvent)="receiveBusinessCycle($event)"></d-table>

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

Is it recommended to utilize the `never` type for a function that invokes `location.replace`?

I'm facing an issue with my TypeScript code snippet: function askLogin(): never { location.replace('/login'); } The TypeScript compiler is flagging an error: A function returning 'never' cannot have a reachable end point. Do ...

Angular4 ChromeDriver Selenium Protractor

I am facing an issue while trying to run 'ng e2e'. The error message I encounter is as follows: WebDriverError: unknown error: cannot find Chrome binary I am using Protractor which is pre-installed with Angular CLI. Despite reinstalling ChromeD ...

Exploring React State Management: Leveraging the Context API as a centralized store for

Currently, I am developing a React web application using TypeScript. To enhance the State Management, I decided to implement React Hooks and Context API by following a concise tutorial that I came across here. Despite diligently following the tutorial, my ...

Instead of displaying the name, HTML reveals the ID

I have defined a status enum with different values such as Draft, Publish, OnHold, and Completed. export enum status { Draft = 1, Publish = 2, OnHold = 3, Completed = 4 } In my TypeScript file, I set the courseStatus variable to have a de ...

Displaying time in weekly view on the Angular 4.0 calendar

I've integrated the library into my Angular application to manage calendar events display and creation. The app features a monthly, weekly, and daily view option for users. However, I noticed that in the weekly view, only the dates are shown without ...

The componentWillReceiveProps method is not triggered when a property is removed from an object prop

Just starting out with React, so I could really use some assistance from the community! I am working with a prop called 'sampleProp' which is defined as follows: sampleProp = {key:0, value:[]} When I click a button, I am trying to remo ...

Before constructing the Spring Boot application, one must first install Node.js

Currently, I am in the process of developing a Spring Boot application with an Angular 4 frontend. To automate the build process, I have set up a pipeline using the AWS developer suite. I have successfully created the pipeline to monitor changes in my rep ...

What is the proper way to create a generic class that can produce various output types while implementing a basic interface?

An abstract class is being created here to transform one type of object into another, with a simple interface comprising id:string and type:string. The intention behind the class definition is to emphasize that it will produce an assembly and during insta ...

NestJS integration tests are failing due to an undefined Custom TypeORM Repository

I am currently facing a challenge while writing integration tests for my Nest.js application. The custom TypeORM repositories in my test context are being marked as undefined. This issue may be occurring because I am not utilizing @InjectRepository. Instea ...

Issue encountered with ASP.Net Core on AWS Serverless: The middleware for the SPA default page was unable to locate and return the default page '/index.html'

Everything works flawlessly with my ASP.Net Core 6.0 application with Angular on Visual Studio, but once deployed to AWS Serverless and accessing '/', an error occurs. The default SPA page middleware cannot serve the default page '/index.h ...

No routes found to match. URL Segment: ''. This issue occurs when attempting to utilize child routes with Angular 2

I am having issues with this specific plunker that seems to not be working correctly. To try and fix the problem, I attempted to comment out a section of code... RouterModule.forRoot([ { path: "", component: TestComponent, ...

The number entered will be incorporated into the API URL key value by passing the variable from page.html to services.ts

Recently diving into the world of Ionic, Angular, and Typescript, I've had a burning question. Can the number inputted be added to the API URL as one of the key values? I came across this helpful guide, specifically focusing on key event filtering (wi ...

Is there a way to identify legitimate contacts and phone numbers within an Android application using Javascript or Typescript?

I am developing an Android app where I need to show a list of contacts and specify if they are part of the app's network. However, my goal is to only display valid contacts while excluding unwanted ones such as toll-free numbers or data balance check ...

Create categories for static array to enable automatic suggestions

I have a JavaScript library that needs to export various constants for users who are working with vscode or TypeScript. The goal is to enable auto-complete functionality for specific constant options. So far, I've attempted to export a Constant in th ...

Challenges encountered when assigning values in a form with Material UI, Formik, and Typescript

When attempting to set the 'role' and 'active' values on a form, I encountered a couple of issues. The first problem arises from the fact that the selectors' original values are not being properly set. These values are fetched in ...

Exploring the Functionality of HTML Anchor Link Fragment within Angular 6

I've been working on an Angular 6 project where I've disabled the hash-location-strategy, removing # from the URL. As a result of this change, a link like: <li routerLinkActive="active"> <a [routerLink]="['/settin ...

Enhancing the theme using material-ui@next and typescript

While developing my theme using material-ui, I decided to introduce two new palette options that would offer a wider range of light and dark shades. To achieve this, I extended the Theme type with the necessary modifications: import {Theme} from "material ...

Exploring the process of enabling full text search on a multi-page encrypted document

I am faced with the task of managing hundreds of documents, each consisting of multiple pages. Users need the ability to search within a document for specific words or sentences. My goal is to retrieve all files that contain the searched text. Currently, ...

Utilizing PrimeNG dropdowns within various p-tree nodes: Distinguishing between selected choices

I am working with a PrimeNg p-tree component <p-tree [value]="treeNodes" selectionMode="single" [(selection)]="selectedNode"></p-tree> The treeNodes are defined using ng-templates, with one template looking li ...

Mongoose encountered an error when attempting to cast the value "ObjectID" to an ObjectId at the specified path "red.s1"

My Mongoose schema is structured as follows: const gameSchema = new Schema({ matchNumber: { type: Number, required: [true, 'A match must have a number!'], unique: true }, red: { s1: { type: ...