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

Using Typescript: Undefined arrays could cause issues in the array map function

Encountering a Typescript error stating that '<array name>' is possibly undefined while attempting to map over an array in Typescript. Below is an example code snippet triggering this issue: type obj = { list?: string[] }; function dem ...

Attempting to integrate the Angular2 module text-mask-addon into the project

Currently, I am in the process of integrating text-mask-addons into my Angular application. You can find more information at https://github.com/text-mask/text-mask/tree/master/addons Despite attempting to follow the npm links suggestion, I am encountering ...

When converting a .ts file to a .js file using the webpack command, lengthy comments are automatically appended at the end of

As a backend developer, I recently delved into UI technologies and experimented with converting TypeScript files (.ts) to JavaScript files (.js) using the webpack command. While the conversion works well, the generated .js file includes lengthy comments at ...

In React Router, redirect when location.state is not defined

import React, { useState } from "react"; import { Redirect } from "react-router-dom"; function Update(data) { if(!data.location.state) return <Redirect to="/"/> const [name, setName] = useState(dat ...

Guide on creating and deploying an iOS API file onto a physical device with a Mac computer

I recently switched to using a Mac and have installed Xcode successfully, along with adding the platform for iOS. However, when I use adb devices, my iPhone device is not detected, but my Android device is recognized when connected. Additionally, when ru ...

The sequence of events in React Native following a navigation.navigate call

Seeking suggestions and advice, I currently have the following 2 lines of code within a react native expo component: this.props.navigation.navigate("App"); patchUser(this.state.dataSource.userInfo.username, this.state.dataSource.userInfo.firstN ...

HTML: Mark the chosen hyperlink or tag

In my HTML page, I am looking to keep the link selected when it is clicked on. Here is the initial HTML code: <table class="main-dev"> <tr> <td> <a class='titleForm' style="cursor:pointer"> ...

How to Delete Multiple Rows from an Angular 4 Table

I have successfully figured out how to remove a single row from a table using splice method. Now, I am looking to extend this functionality to remove multiple rows at once. html <tr *ngFor="let member of members; let i = index;"> <td> ...

Removing outlines on <p> <a> or <div> elements with Ionic and Angular seems to be a challenging task

Hey there, I’m currently working on my application which includes a login page. I've implemented a “Forgotten password ?” link, but no matter what I try, like using .class and :focus {outline: none}, I still see a yellow square around the item. ...

Restricting enum type to only one member

enum Value { First, Second, } interface Data { value: Value number: number } interface SubData { value: Value.Second } function calculation(input: SubData){ return; } function initiate(){ const input : Data = { numbe ...

Angular 2 is throwing an error because it is unable to access the property 'comments' of an undefined value

After ensuring that all {{article.}} properties are functioning properly and displaying correctly on the webpage, there seems to be an issue with article.comments (located at the bottom of the HTML) showing as undefined even though it is the input for the ...

Slim API receives a request from Ionic 5

Seeking assistance with making a GET request from my Ionic application to an API constructed using the Slim Framework. Below is the code snippet of the API: <?php header('Access-Control-Allow-Origin: *'); header('Content-Type: applicati ...

Dynamic Angular components and their content projection

Can content projection be utilized in Angular 2 components that are dynamically loaded and created at runtime, rather than being known at compilation time? ...

show additional worth on the console

Just starting out with JavaScript. Trying to display additional values in the console. Uncertain about how to access add-ons. Can anyone help me troubleshoot? Here is my code snippet below: https://jsfiddle.net/6f8upe80/ private sports: any = { ...

Is it possible to turn off Angular CLI ng build linting for a specific directory?

I am facing an issue with a specific directory in my project template that I want to exclude from linting. Despite excluding it in both tsconfig and eslint, running eslint works fine but when using ng build, the directory is still included in linting and e ...

The comparison between client-side and server-side programming logic

Looking for guidance in website development as I am unsure of where to place my logic. Let's consider a scenario: when a user selects filters, such as price range or home type on a real estate website like Zillow, the list of houses gets updated accor ...

Unexpected behavior observed with field alignment

I've been attempting to align the field in an Angular HTML page, but it's not working out as I expected. Here's how the HTML file looks: <div id="report-prj-search"> <div class="dx-fieldset flex-column"> <div class="fle ...

Handle and manage errors within the controller in Express.js to prevent the further execution of asynchronous functions

Consider a scenario where there is an API endpoint /register, designed to register new users in an application. The function utilized is asynchronous, as an attempt is made to incorporate an asynchronous process within an AuthController when performing pas ...

Creating a specialized feature for saving form data with React Admin

Within my react-admin application, I am faced with a scenario where I have a list of items accompanied by two separate buttons: "Create using email" and simply "Create". The "create" button utilizes the functionality provided by the data provider, which is ...

Issue with nestjs build due to ts-loader module in dev-dependency

I've encountered a Module Error with ts-loader during a docker build ERROR [6/6] RUN nest build 3.9s ------ > [6/6] RUN ...