How can I manually listen to Angular 2 events on a dependency injected instance?

Assume I am working with a component:

@Component({selector: 'todo-cmp'})
class TodoCmp {
  @Input() model;
  @Output() complete = new EventEmitter(); // TypeScript supports initializing fields

  onCompletedButton() {
    this.complete.next(); // this triggers an event
  }
}

Now, in another component, I am injecting a copy of this component using Dependency Injection:


...
 class SomeOtherClass(){
    constructor(todoCmp:TodoCmp){
   // How can I listen to events from the injected ToDoCmp instance?
   ...
 }
 ...

Is there a way to manually add an event listener inside "SomeOtherClass" and capture any click events triggered by the dependency-injected instance of ToDoCmp?

Perhaps something like todoCmp.addEventListener('complete', function(e){})?

Or is there a better approach in Angular 2 for achieving this?

Thanks,

Sean.

Answer №1

Initially, EventEmitter.next() was changed to EventEmitter.emit() around the time of alpha-45.

Secondly, the method you should be using is .subscribe()

class AnotherClass(){
  constructor(todoCmp:TodoCmp){
     todoCmp.complete.subscribe((result)=>{
        //result == argument passed into emit()  
     }))
 }

Please note that this information can also be found in the documentation - it is recommended to refer to them, as EventEmitter offers greater capabilities than traditional event listeners.

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

Issue with ScrollBar functionality in IE

Hello, I am experiencing an issue with the vertical scrollbar on the addUser Page. When I try to select multiple values in the dropdown menu, the page length increases but the scrollbar does not function correctly. This problem only seems to occur in Inter ...

How do I maintain the Type<any> throughout my application state in NgRx without compromising on best practices?

Utilizing Angular 11.1.2 and rxjs 6.6.2 I am working on developing an application that dynamically displays a list of components. I have successfully achieved this functionality independently. However, I am currently encountering challenges when transitio ...

Transferring variables between vanilla JS and Angular 2: A guide

I am facing a challenge where I need to retrieve an object title from vanilla JavaScript and then access it in my Angular 2 component. Currently, I am storing the variable in localStorage, but I believe there must be a better approach. The issue arises wh ...

Issue with debugging Azure Functions TypeScript using f5 functionality is unresolved

I am encountering issues running my Azure TypeScript function locally in VS code. I am receiving the errors shown in the following image. Can someone please assist me with this? https://i.stack.imgur.com/s3xxG.png ...

How to specify the file path for importing a custom module?

I am currently learning Angular 2 and encountering an issue with importing a custom module that contains interface declarations. Here is my folder structure: https://i.stack.imgur.com/heIvn.png The goal is to import product.interface.ts into a component ...

What is the method to save data into the browser's local storage when the reload button is clicked in AngularJS?

Is there a way to store data into the localstorage in AngularJS when the reload button is clicked? I've tried using the code below, but it doesn't seem to work: window.onbeforeunload = function (event) { var $body = angular.element(documen ...

Issue encountered while utilizing combineReducers: "Error: The assetsReducer returned an undefined value during initialization."

Issue: The "assetsReducer" has returned an undefined value during initialization. When the state passed to the reducer is undefined, it must explicitly return the initial state, which cannot be undefined. If no value is set for this reducer, consider using ...

Error: It is not possible to assign a value to the Request property of the Object since it only has a getter method

Encountering issues while attempting to deploy my Typescript Next.js application on Vercel. The build process fails despite functioning correctly and building without errors locally. Uncertain about the root cause of the error or how to resolve it. The f ...

Issue: React child components cannot be objects (received: object with keys)

Hey everyone, I could really use some help figuring out what I'm doing wrong. Here is the error message I'm receiving: Error: Objects are not valid as a React child (found: object with keys {id, title, bodyText, icon}). If you meant to render a ...

ng2-table ways to customize the appearance of a particular row

Hey there, I'm currently new to Angular 2 and working with ng2-table. I've successfully added a table like the one shown here to my website. Now, I'm trying to figure out how to add color to specific rows within the table. Following the ste ...

When downloading text using Angular, the file may not display new line characters correctly when opened in Notepad

When downloading text data as a .txt file in my Angular application using JavaScript code, I encountered an issue. Below is the code snippet: function download_text_as_file(data: string) { var element = document.createElement('a') eleme ...

Bidirectional data binding in Angular 2 allows for communication between parent components and directives

Update: Experimenting with Angular2 Beta, I am working on incorporating an "editor" component template that includes a directive wrapping the Ace editor. In this scenario, the "editor" component acts as the parent of the Ace wrapper directive, and my goal ...

Create a conditional statement based on the properties of an object

In one of my Typescript projects, I am faced with the task of constructing a dynamic 'if' statement based on the data received from an object. The number of conditions in this 'if' statement should match the number of properties present ...

Encountering issues with installing Angular using npm due to errors

When I run npm install, I encounter errors. Though I can get it to work by using npm install --force, I prefer not to rely on the force flag. After reading through the errors, it seems like there might be a version compatibility issue, but I'm having ...

Transmitting data from Angular to .NET Core for seamless integration

I have been attempting to send an xls or any other file from my angular application to a .NET core controller, but none of my methods seem to work... Below is my component where I call my service upon button click: handleFileInput(file: FileList) { this. ...

Standards for coding across different languages

As I work on developing a framework that accommodates both C# and TypeScript, I am faced with an interesting dilemma. Take, for instance, the Validator class in C#: class Validator { public bool Validate(string value) { return someConditi ...

Unable to post links on Facebook when using Angular 7

Is it possible to share a URL on Facebook using Angular 7 without server-side rendering like Angular Universal or prerender? I attempted to update meta tags for Facebook share during the click function, but it did not work. What is the most effective way t ...

The parameter 'prev: todoType[] => todoType[]' cannot be assigned to the type 'todoType[]'.ts(2345)

An issue has arisen with this.props.update as mentioned in the title import { useState } from "react"; import axios from "axios"; import { todoType } from "../../types/todo"; type sendResponse = { task: string; }; type getRe ...

Using TypeScript to deserialize various types from a shared object

I am currently dealing with a JSON array containing serialized objects, each of which has a type field. My challenge lies in deserializing them properly due to TypeScript not cooperating as expected: Check out the TypeScript playground for reference. type ...

Did not adhere to regulations

Currently, I am in the process of developing a React app. However, when I attempt to initiate my project using npm start in the terminal, I encounter an error message on the browser. https://i.stack.imgur.com/wej1W.jpg Furthermore, I also receive an erro ...