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

Eliminate the alert message that appears when dynamically rendering a React styled component

When checking the browser console, I noticed a warning that reads as follows: react_devtools_backend.js:3973 The component styled.div with the id of "sc-dmRaPn" has been created dynamically. You may see this warning because you've called sty ...

A more efficient method for refreshing Discord Message Embeds using a MessageComponentInteraction collector to streamline updates

Currently, I am working on developing a horse race command for my discord bot using TypeScript. The code is functioning properly; however, there is an issue with updating an embed that displays the race and the participants. To ensure the update works co ...

Is there a more efficient method for invoking `emit` in Vue's Composition API from an external file?

Is there a more efficient way to access the emit function in a separate logic file? This is my current approach that is functioning well: foo.js export default (emit) => { const foo = () => { emit('bar') }; return { foo }; } When ...

I am experiencing some issues with the functionality of the Bootstrap carousel on my website's homepage

I've been working on creating an image carousel with Bootstrap 4, but I'm running into some issues. The images aren't sliding properly, and the cursor to change slides isn't functioning correctly. Additionally, the slides seem to repeat ...

Typescript Angular2 filtering tutorial

In Angular 2 using TypeScript, the goal is to search for matching values from an array within an object array. The intention is to filter out any objects where the 'extraService' property contains any of the values from the 'array_values&apo ...

Setting the Node.js version in Eclipse on a Windows operating system can be easily accomplished by following these

After attempting to execute "ng serve" within Eclipse, an error message is displayed: The error states that you are currently using Node.js version v6.9.4, which is not compatible with Angular CLI 8.0+. To successfully use Angular CLI, you need to have No ...

The information in the map cannot be inferred by Typescript based on the generic key type

I encountered a TypeScript issue while refactoring an existing feature in my app. It seems that TypeScript is having trouble picking up the correct type when passing the generic type through nested functions. enum App { AppOne = 'app-one', A ...

Tips for configuring the cookie expiration date using the ngx-cookie-service library

Can anyone offer assistance with setting the expire date for cookies in my Angular 5 app using ngx-cookie-service? Here is what I have tried: setCookies($event){ this.cookieService.set( 'retailAppCookies', "true", 30 ); this.cook ...

Executing the cucumberjs + playwright tests after starting the angular app using the ng serve command

Our testing process involves using cucumberjs and playwright. Is it possible to initiate Angular with ng serve (using test configuration) before running our tests, and then close the application once the tests are complete? Similar to configuring a web s ...

Angular form group not providing data upon submission

Encountering a peculiar issue here. When the submit button is clicked, my angular form group does not return anything. Additionally, nothing is being logged to the console upon clicking. Interestingly, this form is almost identical to another one that func ...

Analyzing arrays and object key/value pairs based on a specific value in javascript

I want to create a new object with key/value pairs. The new object should include values from an existing key/value object as well as unique values from an array. Here is the array: [{ name: "Computer", name: "Car", name: "House&q ...

The functionality of ngModel seems to be malfunctioning when used within select options that are generated inside

I'm currently working on dynamically adding options to an HTML select element within a for loop. I am using [(ngModel)] to get the selected option, but initially no option is pre-selected. Here's a snippet of the code: <table align="center"& ...

The issue of process.server being undefined in Nuxt.js modules is causing compatibility problems

I've been troubleshooting an issue with a Nuxt.js module that should add a plugin only if process.server is true, but for some reason it's not working as expected. I attempted to debug the problem by logging process.server using a typescript modu ...

Is it possible to automatically set focus on the input box in an html tag multiple times instead of just once with autofocus?

Currently, I am developing an online editor that allows users to quickly edit individual words. My approach involves replacing specific words with input boxes containing the word for direct editing by users. In order to streamline the process and ensure e ...

Utilize nodemailer in Angular 6 to effortlessly send emails

I am currently experiencing an issue with my email service form in my Angular 6 application integrated with Node.js. I have set up the form using Bootstrap and Nodemailer for sending emails, but it seems to not be working as expected. Whenever I attempt to ...

In Angular Mat Stepper, only allow navigation to active and completed steps

For a project, I created a sample using React.js and Material UI. Here is the link to the project: https://stackblitz.com/edit/dynamic-stepper-react-l2m3mi?file=DynamicStepper.js Now, I am attempting to recreate the same sample using Angular and Material, ...

Make the width of a table column match the width of the header

I am currently using Primeng2 datatable and I am looking to adjust the column width to match the header size. This is my HTML code: <p-dataTable #dtselfcollectmonthly [exportFilename]="exportname" [rows]="10" [value]="rawdatatrucks"> <ng-con ...

Ways to integrate user input into the header of an Angular HTTP post method

I need help figuring out how to incorporate user input into the header of a post method I am working with. I understand that some kind of binding is necessary, but I'm struggling to implement it in this case. Currently, I have a variable called postDa ...

Ways to access UserProfile in a different Dialogio

For the implementation of a chatbot, I am utilizing Microsoft's Bot Builder framework. However, upon implementing an alternative path to the dialog flow, I noticed that the user's Profile references are getting lost. Here is the code snippet fr ...

Looking to retrieve the smallest amount of array sets in Angular4

I'm currently developing an Angular 4 application and facing an issue with a function I'm trying to write. The goal is to extract the minimum and maximum numbers from three array objects. The yAxisData object consists of three yaxis array objects ...