Are you looking to discontinue receiving updates from the @Output EventEmitter?

Explore the Angular website where you can find a demonstration of communication between Parent and Child components through

@Output() onVoted = new EventEmitter<boolean>();
. Check it out below.

In this specific scenario, is it necessary to unsubscribe from the EventEmitter in order to prevent memory leaks or excessive memory usage? Or does the Framework automatically handle this for you?

component-interaction/src/app/voter.component.ts

import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'app-voter',
  template: `
    <h4>{{name}}</h4>
    <button (click)="vote(true)"  [disabled]="voted">Agree</button>
    <button (click)="vote(false)" [disabled]="voted">Disagree</button>
  `
})
export class VoterComponent {
  @Input()  name: string;
  @Output() onVoted = new EventEmitter<boolean>();
  voted = false;

  vote(agreed: boolean) {
    this.onVoted.emit(agreed);
    this.voted = true;
  }
}

component-interaction/src/app/votetaker.component.ts

import { Component }      from '@angular/core';

@Component({
  selector: 'app-vote-taker',
  template: `
    <h2>Should mankind colonize the Universe?</h2>
    <h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
    <app-voter *ngFor="let voter of voters"
      [name]="voter"
      (onVoted)="onVoted($event)">
    </app-voter>
  `
})
export class VoteTakerComponent {
  agreed = 0;
  disagreed = 0;
  voters = ['Mr. IQ', 'Ms. Universe', 'Bombasto'];

  onVoted(agreed: boolean) {
    agreed ? this.agreed++ : this.disagreed++;
  }
}

Answer №1

When you come across examples on the Angular website where they do not unsubscribe, it may lead you to question why you should bother doing so yourself.

Angular actually takes care of this for you.

Upon creating a directive instance, Angular automatically subscribes to the outputs:

if (def.outputs.length) {
    for (let i = 0; i < def.outputs.length; i++) {
      const output = def.outputs[i];
      const subscription = instance[output.propName !].subscribe(
          eventHandlerClosure(view, def.parent !.nodeIndex, output.eventName));
      view.disposables ![def.outputIndex + i] = subscription.unsubscribe.bind(subscription);

https://github.com/angular/angular/blob/235a235fab45b2c82f8758fc9c0779f62a5b6c04/packages/core/src/view/provider.ts#L138-L140

Furthermore, when a component is destroyed, Angular will automatically unsubscribe from its output subscriptions as well:

export function destroyView(view: ViewData) {
  ...
  if (view.disposables) {
    for (let i = 0; i < view.disposables.length; i++) {
      view.disposables[i]();

Therefore, each time you destroy your directive, Angular will handle the disposal of all subscriptions on your behalf.

However, if you manually subscribe to an EventEmitter in your code, remember to also unsubscribe yourself.

Answer №2

In my opinion, there is no requirement to unsubscribe in this scenario. By not utilizing child to parent component iteration for data retrieval from the API, the need for unsubscribing is eliminated.

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

The RxJS race function comes to a standstill if neither stream completes

Consider the code snippet below: import { interval, race, Subject } from 'rxjs'; import { mapTo } from 'rxjs/operators'; const a$ = new Subject<number>(); const b$ = interval(1000).pipe(mapTo(1)); race([a$, b$]).subscribe(consol ...

Unable to resolve the Typescript module within a different file

I am in the process of transitioning my React app to TypeScript. Currently, everything is working fine. However, I encountered an issue after adding the TypeScript compiler and renaming files to .ts and .tsx extensions - it is now throwing a "module not fo ...

Using the increment operator within a for loop in JavaScript

this code snippet causes an endless loop for (let i = 0; ++i;) { console.log(i) } the one that follows doesn't even run, why is that? for (let i = 0; i++;) { console.log(i) } I want a thorough understanding of this concept ...

Step-by-step guide on integrating jQuery-ui with Asp Core+ Angular 4 template using Visual Studio 2017

Using the Asp Core+webpack+ Angular 4 template from VS 2017, I am trying to figure out how to load jQuery-ui. I attempted to put it in webpack.config.vendor.js: const treeShakableModules = [ '@angular/animations', '@angular/common&a ...

What is the significance of `new?()` in TypeScript?

Here is a snippet of code I'm working with in the TypeScript playground: interface IFoo { new?(): string; } class Foo implements IFoo { new() { return 'sss'; } } I noticed that I have to include "?" in the interface met ...

Encountering an issue in an Angular project where it remains stuck at the preloader stage

Whenever I attempt to redirect to the home page, the URL path changes but the preloader continues to load without rendering the home page until I hard reload the page. Even when I remove the preloader, the page still does not render until I hard reload it. ...

Modifications made in SQL are not reflected in Angular when using .NET Core

I recently encountered a challenge with my project, which is built on .NET Core 3.1 and Angular 7. After migrating the project to a new server, I started experiencing issues related to data synchronization between SQL database changes and the Angular compo ...

how to adjust the width of a window in React components

When attempting to adjust a number based on the window width in React, I encountered an issue where the width is only being set according to the first IF statement. Could there be something wrong with my code? Take a look below: const hasWindow = typeof ...

Error: The element 'mdb-icon' is not recognized and cannot be parsed

I am currently utilizing Angular 7 alongside Bootstrap 4, and encountering the following error message in my console. Uncaught Error: Template parse errors: 'mdb-icon' is not a known element: If 'mdb-icon' is an Angular co ...

In Angular 6, triggering a reset on a reactive form will activate all necessary validators

As a beginner in angular 6, I am currently facing an issue with resetting a form after submitting data. Although everything seems to be functioning properly, when I reset the form after successfully submitting data to the database, it triggers all the req ...

Angular 5: Sharing a Singleton Service Across Components in a Lazily Loaded Feature Module

I'm currently utilizing Angular 5 and have implemented a feature module with routing that is configured for lazy loading. I have reached a point where I need to share a single instance of a service, located within the feature module, between two compo ...

Problem with loading image from local path in Angular 7

I'm having trouble loading images from a local path in my project. The images are not rendering, but they do load from the internet. Can someone please help me figure out how to load images from a local path? I have already created a folder for the im ...

Error: Unable to access $rootScope in the http interceptor response function

I have set up an interceptor to display an ajax spinner while loading. interface IInterceptorScope extends angular.IRootScopeService { loading: number; } export class Interceptor { public static Factory($q: angular.IQService, $ro ...

Obtaining the attribute value of a disabled element in an Angular JS application

Currently, I am struggling to retrieve the attribute value of a disabled element during runtime and then assert its value. The code I'm using is not providing the desired result: softAssert.assertFalse(shrSub.nextButton().waitForPresent().getAttribu ...

I require the ability to identify and capture the ID of the button (touchable opacity) that has been

When trying to delete a selected button by obtaining its specific id, I am facing an issue where after the first execution, the id of the deleted item is retained instead of the newly selected one. I am in need of a solution that allows me to retrieve the ...

Leveraging Angular CLI in conjunction with the newest AspNetCore Angular 4 Single Page Application template

I'm currently experimenting with using Angular CLI alongside the latest JavaScriptServices AspNetCore Angular Spa template. In the past, I would simply copy and paste a .angular-cli.json file into my project's root directory, change "root" to "C ...

Tips for locating the beginning and conclusion of a RxJS.ajax request?

I'm utilizing the RxJS.ajax call to verify the availability of a product in the database. The response from this call typically takes between 2 to 4 seconds. During that retrieval time, I would like to show a message indicating "searching for product" ...

Error: Could not inject CookieService - No provider found for CookieService

I am currently working on an ASP.NET Core 2.0 project that incorporates an Angular 5.1.0 ClientApp in Visual Studio 2017 v15.4.5. My goal is to utilize the ngx-cookie-service within this setup. After closely following the provided instructions for importi ...

Angular form that incorporates a switcher along with a single input field

I have a component with a switcher for different parts, where the user needs to fill input fields (T1, T2, T3). T1 is initially open. Previously, the user filled Part 1, clicked submit, then moved to T2 - submit, and then T3 - submit. Now, I want to send t ...

Typescript's identification of a dispute between RequireJS and NodeJS definitions

I obtained the Typescript RequireJS definition from Definitely Typed. It includes an ambient declaration of Require that clashes with the NodeJs command "require". See below for the declaration and the error message: Declaration: declare var require: Req ...