Invoke the ngOnInit method in Angular 7 or any other method within the component itself

My current dilemma involves a component named user-table-list, which essentially represents a table with entries corresponding to various users.
Within this setup, there exists another component called table-list, responsible for defining the structure and behavior of tables for multiple components (including user-table-list). The HTML code for user-table-list looks like this:

<app-table-list #table [tableConfiguration]="usersTableConfiguration"></app-table-list>

On the other hand, the HTML code for table-list contains the layout details such as columns, headers, etc. The configurations specific to each individual table, including data loading and column names, are defined in the corresponding .ts file.

In the header section, there is a button for adding new entries to the table, whether they are users, clients, or any other entity. The event handling and database operations take place within table-list.component.ts, where different actions are executed based on the type of table the event originates from. Here's an example snippet:

createNewButtonClicked(tableType: string) {
    
    const dialogConfig = new MatDialogConfig();
    dialogConfig.width = '60%';
    dialogConfig.autoFocus = true;

    switch (tableType) {
        case 'clients': {
            this.dialog.open(ClientDialogComponent, dialogConfig);
            break;
        }
        case 'projects': {
            this.dialog.open(ProjectDialogComponent, dialogConfig);
            break;
        }  
        case 'users':{
            this.dialog.open(UserDialogComponent, dialogConfig);
            break;
        }
    }
}

When a new client/project/user is added through these dialogs, I aim to refresh the list by triggering a method that retrieves data from the database. However, the challenge lies in finding a way to trigger this refresh externally without resorting to page reloads. Attempts to achieve this directly in the dialog or table-list components have failed due to circular references. Even creating an external service for this task results in the same issue.

I'm currently at a loss for solutions; how can this desired functionality be implemented without modifying the existing application architecture?

Answer №1

When utilizing a material dialog, you can monitor an observable to determine when the dialog has been closed. By assigning it to a variable, you can track its status as follows:

createNewButtonClicked(tableType: string) {
    // your existing logic
    // ... 
    const dialog = this.dialog.open(ClientDialogComponent, dialogConfig);
    
    dialog.afterClosed().subscribe(closeResult => {
        // update data from database after dialog closure
    });
}

By using an Output property, you can communicate events within a child component to its parent. Within the subscription function (where the database update comment is placed), you can emit that the dialog has been closed. Your list code could resemble the following: @Output() dialogClosed = new EventEmitter();

createNewButtonClicked(tableType: string) {
    const dialogConfig = new MatDialogConfig();
    dialogConfig.width = '60%';
    dialogConfig.autoFocus = true;
    let dialog;
    
    switch (tableType) {
        case 'clients': {
            dialog = this.dialog.open(ClientDialogComponent, dialogConfig);
            break;
        }
        case 'projects': {
            dialog = this.dialog.open(ProjectDialogComponent, dialogConfig);
            break;
        }  
        case 'users':{
            dialog = this.dialog.open(UserDialogComponent, dialogConfig);
            break;
        }
    }
    
    if (!!dialog) {
        dialog.afterClosed().subscribe(closeResult => {
            this.dialogClosed.next();
        });
    }
}

In your user-table component, listen for the event being emitted:

<app-table-list (dialogClosed)="onDialogClosed($event)"></app-table-list>

Lastly, adjust your user tables ts file. Avoid calling ngOnInit again after dialog closure, as ngOnInit should only be used for initialization purposes. Extract the database logic from ngOnInit into another method and trigger it upon dialog closure:

ngOnInit() {
  this.getData();
}

onDialogClose() {
    this.getData();
}

private getData() {
  // perform database operations here and update data accordingly
}

Reserve ngOnInit solely for view initialization to prevent unintended resetting of values previously set.

Answer №2

To trigger an action when the submit button inside the Dialog is clicked, you need to capture the click event of the Dialog and notify the parent components from table-list.

Here's an example:

table-list.component.ts

@Output() clickedOkDialog = new EventEmitter<boolean>();

onClickOkDialog() {
  this.clickedOkDialog.emit(true);
}

Then you can handle the event in user-table-list

In your user-table-list.component.html

<app-table-list (clickedOkDialog)="onClickOkDialog($event)" #table [tableConfiguration]="usersTableConfiguration"></app-table-list>

In your user-table-list.component.ts

onClickOkDialog(event) {
   // Update database after the dialog is closed
}

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

Generate an automatic "proxy" for ASP.NET MVC Controller to communicate with AngularJs service

Whenever I utilize an ASP.NET MVC controller with AngularJS, the majority of my controller functions consist of JSON results. When creating my AngularJS service, I find myself repeatedly writing similar code to handle GET or POST calls to my ASP.NET contro ...

Generating conference itinerary - establishing agenda function (Sequelize)

const _ = require('lodash'); const Promise = require('bluebird'); const Sequelize = require('sequelize'); const ResourceNotFound = require('./errors').ResourceNotFound; const ResourceAccessDenied = require('./er ...

I constantly receive null values when executing my database query function

I created a query function for my project, but the result always comes back as null. How can I troubleshoot this code? const queryDB = async (collection, filter) => { let result = null await MongoClient.connect(url, function(err, getDb) { if ...

retrieve the classname by tapping into the parsed JSON

Being a newcomer to this technology, I am embarking on my first project. My task involves calling an API and receiving a large parsed JSON file. Within this extensive JSON response (which contains HTML code), I need to extract a specific class from the te ...

How can you recognize the attribute modification event in KnockoutJS?

Can the attribute change event be identified in KnockoutJS? I came across solutions in jQuery: Firing event on DOM attribute change . However, it would be ideal if I could achieve this using KO. ...

The controller's AngularJS function seems to be unresponsive

Issue with AngularJs ng-click Event I'm attempting to utilize the GitHub Search-API. When a user clicks the button, my Controller should trigger a search query on GitHub. Here is my code: HTML: <head> <script src="js/AngularJS/angula ...

What is the process for activating namespacing on a VueX module that has been imported?

I am currently utilizing a helper file to import VueX modules: const requireModule = require.context('.', false, /\.store\.js$/) const modules = {} requireModule.keys().forEach(filename => { const moduleName = filename ...

Can you explain the concept of static in Typescript?

Exploring the distinctions between the static and instance sides of classes is addressed in the Typescript documentation on this page. The static and instance sides of classes: understanding the difference In object-oriented programming languages like ...

After the "div" tag comes the magic of AJAX, PHP, and JAVASCRIPT, replacing

My Ajax implementation is successfully displaying the selected content on a div, but unfortunately, everything that comes after the div is getting replaced by this output. I am unsure of why this is happening and how to resolve it. If you have any insigh ...

Enhance your automation with the powerful combination of Java,

I am looking to retrieve data from a specific Russian gambling website using String information. Below is the code I have written for this purpose: import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.ope ...

Unable to save text to file in both Javascript and PHP

I'm facing an issue with my website signup form. It consists of fields for email and password. The HTML triggers a JavaScript function which, in turn, calls PHP code to save the email to a file on the server. While the JavaScript seems to be functioni ...

The toggle-input component I implemented in React is not providing the desired level of accessibility

Having an accessibility issue with a toggle input while using VoiceOver on a Mac. The problem is that when I turn the toggle off, VoiceOver says it's on, and vice versa. How can I fix this so that VoiceOver accurately states whether the toggle is on o ...

Safari Glitch in Bootstrap 4

For a simplified version, you can check it out here: https://jsfiddle.net/dkmsuhL3/ <html xmlns="http://www.w3.org/1999/xhtml"> <title>Testing Bootstrap Bug</title> <!-- Bootstrap V4 --> <link rel="stylesheet" href="https://m ...

Compiling Typescript tasks in Visual Studio Code - ensuring output encoding is set correctly

Have you tried manually setting up a typescript compilation task in Visual Studio Code? You can find detailed instructions at this link. When you run the build command (Ctrl+Shift+B), are you seeing an error message from tsc with unknown encoding? Check o ...

An error occurred: Cannot access the 'splice' property of an undefined value

//Screenshot <div v-for='(place) in query.visitPlaces' :key="place.name"> <div class="column is-4 is-narrow"> <b-field label="Nights"> <b-input type="text" v-model="place.nights" placeho ...

Position the <a> to the right side of the div

Is there a way to right-align the <a> element, which contains a Button with the text Push Me, within the <div> (<Paper>)? https://codesandbox.io/s/eager-noyce-j356qe This scenario is found in the demo.tsx file. Keep in mind that using ...

What steps should I take to resolve the error: Uncaught SyntaxError: expected expression, received '<'?

I'm facing an issue with my code. It works perfectly on my computer, but when I move it to the server, I encounter the following error. Error: Uncaught SyntaxError: expected expression, got '<' Here is the code snippet causing the prob ...

The JavaScript function is unable to fetch information from the controller

I am working with a controller called Map1 that returns a JSON object. Within my scripts folder, there is a .js file named init.js. In this file, I am attempting to call the controller using the following code: $(document).ready(function() { $.getJSO ...

The moduleResolution setting is missing in the tsconfig.json file generated by Next.js TypeScript

Currently, I am in the process of migrating my existing Next.js project to TypeScript. To do this successfully, I have installed various TypeScript related packages by running the following command: npm install --save-dev typescript @types/react @types/nod ...

In Angular, components can be appended to the page instead of replacing the entire page when using router-out

After exploring all related inquiries and their accepted solutions on stackoverflow, I found that none of them worked for me. My current Angular version is 8.1.3. The issue I am facing is that when I click on a routerLink, my component gets appended to th ...