Tips for incorporating a child's cleaning tasks into the parent component

I am working with a parent and a child component in my project. The parent component functions as a page, while the child component needs to perform some cleanup tasks related to the database.

My expectation is that when I close the parent page/component, the order of execution should be:

child ngOnDestroy -> child cleanWork -> parent ngOnDestroy.

However, in reality, the sequence looks like this:

child ngOnDestroy -> parent ngOnDestroy.

// parent

@Component({
  selector: 'parent',
  template: `
    <child
     (cleanWork)="onCleanWork()">
    </child>
  `
})
export class ParentComponent {
  ngOnDestroy() {
    console.log('parent ngOnDestroy');
  }

  onCleanWork() {
    console.log('child cleanWork');
    // dispatch an action, or do something with database
  }
}

// child

@Component({
  selector: 'child',
  template: `Hi`
})
export class ChildComponent {
  @Output() cleanWork = new EventEmitter();

  ngOnDestroy() {
    console.log('child ngOnDestroy');
    this.cleanWork.emit(null);
  }
}

The reason I have chosen to handle the cleanup work within the child component is because I want to keep the child component dumb. Are there any alternative or better approaches for achieving this? Thank you

Answer №1

To establish a connection between a subordinate and its superior:

@ViewChild(SubordinateComponent) subordinate: SubordinateComponent;

Then, trigger the cleanup process from the superior when necessary (in your ngOnDestroy)

ngOnDestroy() {
  subordinate.cleanup();
}

Answer №2

I received assistance from Brandt B. @babeal on Gitter.

While utilizing ngrx/store, it is recommended to handle all database-related actions in the parent smart component rather than emitting them from the child component first and then triggering an action in the parent.

In this scenario, it is best practice to perform the necessary tasks directly within the parent component.

For further insight, you can refer to Presentational and Container Components.

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

How to redefine TypeScript module export definitions

I recently installed a plugin that comes with type definitions. declare module 'autobind-decorator' { const autobind: ClassDecorator & MethodDecorator; export default autobind; } However, I realized that the type definition was incorrec ...

The message states that the variable "Chart" has not been defined

I have been attempting to integrate ChartJS with Angular2, but I keep encountering an error message stating that 'Chart is not defined'. I made sure to install the ChartJS typings and referenced them accordingly. Additionally, I included the char ...

Encountering a Difficulty while attempting to Distinguish in Angular

I am currently working on a form where I need to dynamically add controls using reactiveForms. One specific task involves populating a dropdown menu. To achieve this, I am utilizing formArray as the fields are dynamic. Data: { "ruleName": "", "ruleD ...

Tips for preventing the exposure of internal components in Angular

Imagine an OutlookBarComponent that contains various bars similar to those seen in Microsoft Outlook. Each bar has a child component called OutlookBarItemComponent. Both the OutlookBarComponent and OutlookBarItemComponent are encapsulated within the Contro ...

Conditions are in an angular type provider with AOT

I am facing an issue with my Angular project that is compiled using AOT. I am trying to dynamically register a ClassProvider based on certain configurations. The simplified code snippet I am currently using is below: const isMock = Math.random() > 0.5; ...

Creating an Angular Universal Dockerfile and docker-compose.yml file: A step-by-step guide

After struggling to Dockerize my Angular universal app and integrate it with an existing dockerized Spring Boot REST backend, I found myself hitting a wall in terms of available resources and assistance online. Despite making various adjustments, the Docke ...

Angular 4 in combination with ngx-datatable is showing a 404 error for the @swimlane/ngx-datatable package

Just starting out with Angular and I kicked things off by running this command: git clone https://github.com/angular/quickstart appName I've made the upgrade to Angular 4 and everything seems to be in order. Here's the output I got after running ...

Peer Dependency Issue Detected in My Angular Project

Whenever I run the command below, I receive the following messages: npm install --save @angular/animations --> +-- UNMET PEER DEPENDENCY @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e3d31332e37323b2c1e6b706c706b" ...

Is there a syntax issue in your Angular/Typescript code?

I am currently developing a login system using Angular and Firestore, and here is the code I have written: import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import * as firebase from 'firebase/ ...

Tips for adjusting the size and positioning the ng bootstrap carousel in the center

My Angular project is using ng bootstrap, but I'm facing a styling issue. The content doesn't display in the center, rather it appears in the upper left corner: example I would like the content to be centered and wide under the blue headbar. W ...

The Angular HTTP request is coming back with a status of 0, even though I was anticipating

I need to access a server with various routes. The routes are as follows: app.use('/401', (req, res) => res.status(401).end()); app.use('/403', (req, res) => res.status(403).end()); app.use('/404', (req, res) => res. ...

What is the method for substituting one text with another using two-way data binding?

I implemented two different cases in my Mat-Table. When there is no data, the user will see a message saying "No Data Found". However, if the user enters text in the filter search, the "No Data Found" message should be hidden and replaced with the entered ...

What is the best way to pass a value to a modal and access it within the modal's component in Angular 8?

How can I trigger the quickViewModal to open and send an ID to be read in the modal component? Seeking assistance from anyone who can help. Below is the HTML code where the modal is being called: <div class="icon swipe-to-top" data-toggle="modal" da ...

Error in TypeScript code for combined Slider and Input onChange functionality within a Material-UI component

HandleChange function is used to update the useState for Material-UI <Slider /> and <Input />. Here is the solution: const handleChange = (event: Event, newValue: number | number[]) => { const inputValue = (event.target as HTMLInputEle ...

The TypeScript error reads: "An element is implicitly assigned the 'any' type because an expression of type 'any' cannot be used to index a specific type."

[Hey there!][1] Encountering this TypeScript error message: { "Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ 0: { image: string; title: string; text: string; }; 1: { ...

Derive the property type based on the type of another property in TypeScript

interface customFeatureType<Properties=any, State=any> { defaultState: State; properties: Properties; analyzeState: (properties: Properties, state: State) => any; } const customFeatureComponent: customFeatureType = { defaultState: { lastN ...

Creating one-to-one relationships in sequelize-typescript can be achieved by setting up multiple foreign keys

I have a question about adding multiple foreign keys to an object. Specifically, I have a scenario with Complaints that involve 2 Transports. One is used to track goods being sent back, and the other is used for goods being resent to the customer. @Table({ ...

What's the issue with conducting a unit test on a component that has dependencies with further dependencies?

I am experiencing an annoying error that seems to be my mistake and I cannot figure out how to resolve it. The issue lies within a simple component which serves as a top-bar element in my web application. This component has only one dependency, the UserSe ...

Can we specify the type of a destructured prop when passing it as an argument?

I have implemented Material UI's FixedSizeList which requires rendering rows in the renderRow function and passing it as a child to the component. The renderRow function accepts (index, style, data, scrolling) as arguments from the FixedSizeList comp ...

What steps can I take to ensure that AstroJS components do not conceal SVG elements when the SVG is incorporated into another file with client:load?

Currently, I am developing a weather application using Astro.js in conjunction with React. One of the features includes an SVG component that serves as the project logo and is implemented in the initial page loader. Upon the page loading, the SVG functions ...