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

A guide on validating an array of literals by leveraging the power of class-validator and class-transformer through the methods plainToInstance or plainTo

I am struggling with my validation not working properly when I use plainToInstance to convert literals to classes. Although the transformation appears to be successful since I get Array(3) [Foo, Foo, Foo] after using plainToInstance(), the validation does ...

Looking to implement browserDetection functionality in your Angular 4 application?

I am currently in the process of transitioning from Angular2 to Angular4. However, I encountered an error in Angular4: component: import { browserDetection } from '@angular/platform-browser/testing/src/browser_util'; if (browserDetection.isWe ...

Issue with alignment of Ionic 4 toolbar

Has anyone encountered an issue with the toolbar alignment in angular 8/ionic 4? https://i.sstatic.net/QGc6K.png Below is the code snippet for the footer of tab2.page.html: <ion-footer> <ion-toolbar> <ion-buttons start> < ...

Establish a many-to-many relationship in Prisma where one of the fields is sourced from a separate table

I'm currently working with a Prisma schema that includes products, orders, and a many-to-many relationship between them. My goal is to store the product price in the relation table so that I can capture the price of the product at the time of sale, re ...

How to Customize Bootstrap Colors Globally in Angular 4 Using Code

I am interested in developing a dynamic coloring system using Angular. I have set up a service with four predefined strings: success, info, warning, and danger, each assigned default color codes. My goal is to inject this service at the root of my applicat ...

Display an error popup if a server issue occurs

I'm considering implementing an Error modal to be displayed in case of a server error upon submitting a panel. I'm contemplating whether the appropriate approach would be within the catch statement? The basic code snippet I currently have is: u ...

Unable to retrieve shared schema from a different schema.graphql file within the context of schema stitching

In my project, I have a user schema defined in a file named userSchema.graphql; id: String! userName: String! email: String! password: String! } In addition to the user schema, I also have separate schema files for login and register functionalit ...

Verification based on conditions for Angular reactive forms

I am currently learning Angular and working on creating a reactive form. Within my HTML table, I have generated controls by looping through the data. I am looking to add validation based on the following cases: Upon page load, the Save button should be ...

Tips on how to personalize the print layout of an Angular 4 page when pressing ctrl+p

I am working on an angular4 app and I encountered an issue when trying to customize the print page view by pressing ctrl+p in the browser. The page that needs to be printed contains only Angular components, and my attempts to modify the print view using ...

Troubleshooting the Issue with Conditional Rendering in Nextjs & TypeScript

Struggling with rendering a component conditionally. I have a drawHelper variable and a function to toggle it between true and false. The component should render or not based on the initial value of drawHelper (false means it doesn't render, true mean ...

Is there a way to identify which elements are currently within the visible viewport?

I have come across solutions on how to determine if a specific element is within the viewport, but I am interested in knowing which elements are currently visible in the viewport among all elements. One approach would be to iterate through all DOM elements ...

Encountering difficulty in fetching data from a service with ng-select

Currently, I am utilizing ng-select for a form that allows users to search for activities to add. The ng-select component triggers a function whenever something is typed into the field. This function then calls a service that fetches an array of activities ...

The HTTP GET request was successful, however, there is no data being displayed on the screen

I am currently facing an issue with fetching data from a web server. The data is retrieved successfully as I can see the object in the console log, but it does not render in the component template. export class CountrydetailsComponent implements OnInit { ...

What is the alternative method for establishing a child formGroup within a parent formGroup without using the initializer function?

Can anyone help me with dynamically setting a property in my formGroup to another formGroup, essentially creating a child formGroup? // Example 1 var parent = this._formBuilder.group({ id: [''], child: this._formBuilder.group({ na ...

The function argument does not have the property 'id'

I created a function that authorizes a user, which can return either a User object or a ResponseError Here is my function: async loginUser ({ commit }, data) { try { const user = await loginUser(data) commit('setUser', user) ...

The 'in' operator is unable to find 'colour' within true (function return type)

Here's the TypeScript code I'm working with: let a: unknown = true; if(hasColour(a)) { console.log(a.colour); // Using a.colour after confirming a has the colour property } I've created a function to check if the color property exist ...

The attribute 'do' is not defined in the AngularFireList type

Despite coming across numerous similar posts, I am still struggling to comprehend the issue at hand and how to resolve it. posts$: Observable<Post[]> = this.db .list(`posts/${this.uid}`) .do(next => this.store.set('posts', next) ...

What is the best way to ensure that consecutive if blocks are executed in sequence?

I need to run two if blocks consecutively in TypeScript, with the second block depending on a flag set by the first block. The code below illustrates my scenario: export class Component { condition1: boolean; constructor(private confirmationServic ...

Encountering a hiccup while trying to install Svelte, Skeleton, and Tail

Recently entering the world of Svelte and TypeScript, I have encountered some unexpected errors after installation. Despite following the same steps as before, I am puzzled by what is causing these issues. This is the process I followed: npm create svelte ...

What is the best way to display noscript content within my Angular application?

What is the best way to show HTML content for users who do not have JavaScript enabled in my Angular application? Inserting the noscript tag directly into the index.html file does not seem to be effective. <body> <noscript>Test</noscrip ...