What is the process of displaying events from components within ng2 submodules?

My dilemma involves two components with straightforward output events and handlers. I am attempting to pass a value from a child submodule to a component within my app.module. Here is the snippet of code from my app.component.ts:

@Component({
  selector: 'my-app',
  template: `
  <sidebar *ngIf="showHeader" (everySecond)="everySecond()" ></sidebar>
  <navbar *ngIf="showHeader" (toggleNav)="toggleNav($event)"></navbar>
  <router-outlet></router-outlet>`,
  directives: [homeComponent, sidebarComponent, navbarComponent]
})
export class AppComponent {
  everySecond() { console.log('second'); }
}

The issue arises in my app.module.ts where I import tutorialModule containing the tutorial component below.

export class tutorialComponent {
  @Output() everySecond = new EventEmitter();

  constructor() {
    this.everySecond.emit("event");
    console.log("here");
  }
}

Upon navigating to the tutorialComponent, only the "here2 log is printed out while the "second" event is not triggered. It seems that the tutorialComponent is not declared as a directive of the app.component due to being imported as a module. How can I resolve this issue?

Answer №1

It is essential to include everySecond subscription in your main app module:

Here's a simple example:

this.tutorialComponent.everySecond.subscribe((data) => {
   console.log('second');
});

Answer №2

When you trigger the event in the constructor, the data binding is not yet established, so any potential receiver will not be able to detect the event. However, if you move the code to ngOnInit(), the event will be triggered after the component has been initialized and the data binding is set up.

export class tutorialComponent {
  @Output() everySecond = new EventEmitter();

  ngOnInit() {
    this.everySecond.emit("event");
    console.log("here");
  }
}

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

Displaying Typescript command line options during the build process in Visual Studio

As I delve into the world of VS 2015 Typescript projects, I find myself faced with a myriad of build options. Many times, the questions and answers on Stack Overflow mention command line options that I'm not completely familiar with, especially when i ...

When implementing a sizable Angular material popover, ensure that the parent content is designed to allow scrolling

I have a custom popover feature in my current project, which includes checkboxes beneath the main content. Everything is functioning properly at the moment, but I've encountered an issue when the screen's resolution is reduced - the content at th ...

Converting Blob to File in Electron: A step-by-step guide

Is there a way to convert a Blob into a File object in ElectronJS? I attempted the following: return new File([blob], fileName, {lastModified: new Date().getTime(), type: blob.type}); However, it appears that ElectronJs handles the File object differently ...

Is it feasible to alter the TypeScript interface for the default JavaScript object (JSON)?

When dealing with cyclic objects, JSON.stringify() can break (as mentioned in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value) An alternative solution suggested in the same article is to use 'cycle.js&apos ...

The CloudWatch logs for a JavaScript Lambda function reveal that its handler is failing to load functions that are defined in external

Hello there, AWS Lambda (JavaScript/TypeScript) is here. I have developed a Lambda handler that performs certain functions when invoked. Let me walk you through the details: import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda' ...

The element is not defined in the Document Object Model

There are two global properties defined as: htmlContentElement htmlContentContainer These are set in the ngAfterViewInit() method: ngAfterViewInit() { this.htmlContentElement = document.getElementById("messageContent"); this.htmlContentCont ...

Can we rely on the security of Ionic 4 secure storage encryption?

I'm currently developing an application that necessitates the user to be in close proximity to a specific GPS location. At present, I am obtaining their location every 30 seconds, transmitting it to my server, checking if they are near the desired loc ...

Differentiating response.data typing on the front end in Typescript depending on the request's success status

Consider this scenario: A secure API authentication route that I am not allowed to access for viewing or editing the code returns interface AuthSuccess { token: string user: object } on response.data if the email and password provided are correct, but ...

Creating an Http Service Instance in Angular 2 by Hand

Can the Http Service be initialized manually without needing it as a constructor argument? export class SimpleGridServer { private http: Http; constructor(public options: SimpleServerData) { http = new Http(.../* Argument here */); } } ...

I possess a function that can retrieve the key of an Object, but now I am faced with the task of accessing the actual Object using this value in JavaScript

This is my first time seeking advice on a technical issue. I'm currently working with the following function: export function sendRequest<T>(req: RawRequest, options) { const start = Date.now(); const reqOptions: CoreOptions = { ...

When using TypeScript, a typed interface will not permit a value that is not within its specified string literal type

I have downsized my issue to a smaller scale. This class needs to set the default value of its "status" property. The type T extends the string literal type "PossibleStatus" which consists of 3 possible strings. Typescript is giving me trouble with this. ...

Using Typescript to overload functions with varying first parameters

I am facing a scenario where I have a parent class that requires a method implementation with either one or two parameters depending on the child class. class MyClass { update(obj: HashMap); update(id: ID, obj: HashMap); update(objOrId: HashM ...

Efficiently configuring Angular 2 with ng-bootstrap

Hi there, I am currently diving into the world of Angular and Bootstrap, while also exploring node js. My goal is to create a solid foundation using the webpack starter kit available at this link: https://github.com/AngularClass/angular2-webpack-starter ...

RXJS buffering with intermittent intervals

Situation: I am receiving audio data as an array and need to play it in sequence. The data is coming in continuously, so I am using an observable to handle it. Since the data arrives faster than it can be played, I want to use a buffer to store the data w ...

(Typescript) The 'window' property is not present in the 'Global' type

Currently, I am utilizing Mocha/Chai for unit testing and have decided to mock the window object like so: global.window = { innerHeight: 1000, innerWidth: 1000 }; As expected, TSLint is raising an issue stating: Property 'window' does not ex ...

Submit file in Cypress while hiding input[type="file"] from DOM

Currently, I am conducting end-to-end testing on an Angular project that utilizes Ant Design (NG-ZORRO). In this project, there is a button with the class nz-button that, when clicked, opens the file explorer just like an input type="file" element would. W ...

Resolving the global provider in Angular2 Typescript with the help of an Interface

In the realm of my Angular2 application, I have two essential services called WebStorageService and MobileStorageService, both of which impeccably implement an interface known as IStorageService. Interestingly, in my magnificent main.component, I elegantly ...

Tips for navigating to a specific row within a designated page using the Angular Material table

Utilizing angular material, I have set up a table with pagination for displaying data. When a user clicks on a row, they are redirected to another page. To return to the table page, they must click on a button. The issue arises when the user needs to retu ...

Enable Parse5's case sensitivity

Recently, I've attempted to parse Angular Templates into AST using the powerful parse5 library. It seemed like the perfect solution, until I encountered an issue - while parsing HTML, it appears that the library transforms everything to lowercase. Fo ...

Encountering the error "RouterOutletMap provider not found" while using angular-cli version 1.0.0-beta.10

I am facing confusion while trying to set up routing for angular-cli version 1.0.0-beta.10, using @angular/router version 3.0.0-beta.2. I encountered an error message stating 'No provider for RouterOutletMap'. Any assistance in resolving this iss ...