Angular: Failure in receiving EventEmitter's event with .subscribe method

My current challenge involves handling an event coming from NgLoopDirective within the method EV of NgDNDirective. I am attempting to achieve this by passing the EventEmitter object by reference and then calling .subscribe() as shown in the code snippet below:

import { Directive, Input, ElementRef, Renderer2, EventEmitter } from '@angular/core';

@Directive({
  selector: '[ngDN]'
})
export class NgDNDirective {

  private dn: number = -1
  private ev: EventEmitter<void>;

  @Input() set ngDN(dn: number) {
    this.dn = dn
  }

  @Input() set EV(ref: {ev: EventEmitter<void>}) {
    console.log('waiting for ev')
    ref.ev.subscribe(() => {
      console.log('data-num:', this.dn)
      this.renderer.setAttribute(this.elRef, 'data-num', this.dn.toString())
    })
  }

  constructor(private elRef: ElementRef,
              private renderer: Renderer2) {}

}

@Directive({
  selector: '[ngLoop]'
})
export class NgLoopDirective {

  @Input() set ngLoop(iter_count: number) {
    this.container.clear()
    for (let i=0; i<iter_count; i++) {
      let ev: EventEmitter<void> = new EventEmitter<void>()
      let ref = {ev: ev}

      this.container.createEmbeddedView(this.template, {index: i, ev: ref})
      ev.emit()
    }
  }

  constructor(private template: TemplateRef<any>,
              private container: ViewContainerRef) {}

}

Here is how the HTML code is implemented:

<ng-template [ngLoop]="10" let-i="index" let-ref="ev">
  <a href="#" [ngDN]="i" [EV]="ref"></a>
</ng-template>

However, when debugging the code in the console, only the following message is displayed:

waiting for ev

This indicates that the event was not handled successfully since

console.log('data-num:', this.dn)
was not triggered.

What could be causing this issue?

Answer №1

Once you emit an event, Angular will run change detection for NgDNDirective.

If you want to manually trigger change detection, you can do so like this:

const view = this.container.createEmbeddedView(this.template, {index: i, ev: ref});
view.detectChanges();

Check out this Plunker Example

Alternatively, you can use ReplaySubject instead of EventEmitter.

Here's another Plunker Example

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

What is the functionality of Google Chrome's "New Tab" iframes?

Have you ever wondered about those 8 small iframes displaying your most visited websites? How do they capture snapshots of the websites? How are the websites chosen for display? And most importantly, how do they actually work? Edit: I want to learn how to ...

Angular - The confirmDialog from Primeng is appearing hidden behind the modal from ng-bootstrap

I am currently utilizing the primeng and ng-bootstrap components to develop an angular-based website. In order to collect data, I have implemented a form within an ng-bootstrap modal. However, upon clicking the "save" button on the modal, the primeng conf ...

Refreshing a webpage post initial loading using Next.js

Having trouble with my checkout route ""./checkout"" that displays embedded elements from Xola. The issue arises when using client-side routing as the checkout page requires a manual refresh to load correctly and show the Xola elements on the DOM ...

What is the best way to apply focus to a list element using Javascript?

I recently created code to display a list of elements on my webpage. Additionally, I implemented JavaScript functionality to slice the elements. Initially, my page displays 5 elements and each time a user clicks on the "show more" link, an additional 5 ele ...

The error callback in Jquery ajax is triggered despite receiving a 200 status code in the response

I am facing an issue with my ajax code. The success callback contains an alert that is not working properly. Here is the code snippet: $(".change_forex_transaction_status").click(function(){ $("#insufficient_funds").css("display","none"); var id = $( ...

Send the information to MongoDB in the form of an object, utilize it as a query, and then perform

I have a document stored in my mongoDB database. https://i.sstatic.net/2DI2p.png When a user types something into an input field on the frontend, for example 'test', the object passed looks like this: {'countdown': 'test'} ...

Is there a way to convert a JSON input object to a model class using TypeScript in a Node.js application?

Currently, I am developing my Node.js server using TypeScript and the express framework. Here is an example of what my controller and route looks like: export class AuthController { public async signUpNewUser(request: Request, response: Response) { ...

Exploring JSON objects within other JSON objects

As I work on my Angular App and implement angular translate for dual language support, I've encountered an issue with accessing nested items within my JSON object. After carefully constructing my JSON and verifying its validity, I attempt to retrieve ...

How do I redirect with a GET method after calling the *delete* method in Node / Express server?

As someone new to AJAX and Node, I encountered a dilemma that I hope to get some guidance on. Here's the issue: I have a DELETE ajax call that removes a row from the database and I want to redirect back to the same route with a GET method afterwards. ...

Persistently save retrieved information and store data in MongoDB by utilizing Node.js

I am facing the challenge of continuously making an http.get request to an API that provides location data. I have tried a basic get request to test if the data is being received, and it is. However, the issue is that I need this process to run in a contin ...

The UseEffect Async Function fails to execute the await function when the page is refreshed

Having trouble calling the await function on page refresh? Can't seem to find a solution anywhere. Here's the useEffect Code - useEffect(() => { fetchWalletAddress() .then((data) => { setWalletAddress(data); setLoa ...

Form calculation

An issue has arisen with my calculating form for a client where an incorrect amount is displayed when 0.93 is entered into the percentage box. Original calculation: 10 x 10 x 15 x 0.93 = 13.95 Corrected calculation: 10 x 10 x 15 x 0.93 = 1.395 I am seek ...

Error message in Typescript: The argument type '() => () => Socket<DefaultEventsMap, DefaultEventsMap>' cannot be assigned to a parameter of type 'EffectCallback'

I am struggling to comprehend how I should specifically type constrain in order to prevent the error within my useEffect. One approach is to either cast my newSocket or specify the return value of my useEffect as any, but I am hesitant about that solution. ...

A guide on using jCrop to resize images to maintain aspect ratio

Utilizing Jcrop to resize an image with a 1:1 aspect ratio has been mostly successful, but I've encountered issues when the image is wider. In these cases, I'm unable to select the entire image. How can I ensure that I am able to select the whole ...

Guide on associating an array of object keys with an array of their corresponding values within a specified object

const obj = { wheels: 4, lights: 2, doors: 4 } customMapFunction(obj, { properties: ["wheels", "lights"], formatter: (wheels, lights) => `${wheels}-${lights}` // "4-2" }) How do I define the types for customMapFunction in TypeScript to ensure th ...

AngularJS: Issues with retrieving response headers following a $resource $save operation

When I run the $save function, which triggers my angularJS $resource to send a POST request to my API, everything seems to be working fine. I can successfully debug into the success callback handler and confirm that the object is created in my API. myObj. ...

Issue with closing the active modal in Angular TypeScript

Can you help me fix the issue with closing the modal window? I have written a function, but the button does not respond when clicked. Close Button: <button type="submit" (click)="activeModal.close()" ...

In the realm of JavaScript, what happens when a function yields yet another function while also welcoming another function as an argument?

After following a Node & Express project tutorial on YouTube, I encountered the following code snippet in an async JavaScript file: const asyncHWrapper = (fn) => { return async (req, res, next) => { try { await fn(req, res, next); } c ...

Collaborate on a component used in multiple modules

In my application, there are two modules: employer and landing. I have created a component in the landing module that I want to share with the employer module. To achieve this, I declared the component in the app.module.ts file of the parent module and use ...

Having trouble with jQuery.validate.js while using type="button" for AJAX calls in an MVC application

I have come across several questions similar to mine, but I haven't found a solution that fits my situation in MVC, so I am reaching out for help. I am a beginner with MVC and I am utilizing jQuery AJAX to invoke a controller method for data insertio ...