Trigger a re-initialization when there is a change in the @

Can we instruct Angular to execute the init function (or any other lifecycle function or custom function) when the component input changes, or do we need to manually trigger that function from the parent component instead of modifying the input directly?

Appreciate your responses!

Answer №1

Whenever a component's input is changed, the ngOnChanges lifecycle hook is triggered. This allows you to execute any other lifecycle hook or function as needed.

ngOnChanges(...args: any[]) {

    console.log('onChange fired');            
    this.ngOnInit();
}

ngOnInit()
{
    console.log('ngOnInit fired');
}

UPDATE:
In case you need to invoke the child component's ngOnInit from the parent component, you can utilize ViewChild as demonstrated below.

export class Parent{

   @ViewChild(child) vc:child;

    ngAfterViewInit()
    { 
      console.log("ngAfterInit");
      console.log(this.vc.ngOnInit());
    }

};

export class child{

   ngOnInit()
    {
        console.log('ngOnInit fired');
    }
};

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

Issue with directive causing hoverable or clickable tooltip not opening when the tooltip is supposed to be displayed

Incorporating ng-mouseover/ng-mouseleave along with tooltip-is-open to control the state of the tooltip, I have successfully implemented a tooltip that remains open when hovered over. However, when attempting to reorganize it into a directive with ...

Is there a compatibility issue between ui.bootstrap tooltip and ng-model in an input element?

My goal is to incorporate an input element with a tooltip and connect a function to the enter keypress event. Individually, each of these features works, but when combined, they seem to be causing an issue. The following is the code snippet: <input t ...

Unable to display Cell Properties in Angular using CKEditor 5 table toolbar configuration

While utilizing the CKEditor 5 official demo, I noticed that the table content Toolbar includes Cell properties. This feature is crucial for my needs, but despite configuring my table similarly to the demo setup, the Cell properties do not appear. The dem ...

Transferring information from a service to an AngularJS controller

I have a service that retrieves data from a URL provided as a parameter, and it is functioning correctly. However, when attempting to pass this data to a controller's $scope in AngularJS, I am not receiving any data. var app = angular.module("Recib ...

Can NgZone be utilized within a shared service instance?

I am currently working on creating an injectable singleton service for my application that will provide all components with information about the window width and height, as well as notify them when the page is scrolled or resized. Below is the code snipp ...

How to utilize ng-if as a conditional statement within ng-repeat?

I've been working on an Angular application and ran into some trouble trying to use ng-if and switch within an ng-repeat loop. Here is the data structure I'm working with: **[{"_id":"52fb84fac6b93c152d8b4569", "post_id":"52fb84fac6b93c152d8b4 ...

The variable is currently undefined because it has an array assigned to it

Upon selecting multiple checkboxes for variants, I am retrieving checked data using the following method: get selectedIdsFromViolCategoriesFormArray(): string[] { return this.violCategories .filter((cat, catIdx) => this.violCategoriesFormArr. ...

Ensuring Type Safety for Collections in TypeScript

My code snippet looks like this: portfolioList: MatTableDataSource<Portfolio>; ngOnInit(): void { this.backend.getStatement().subscribe( list => { if(list as Portfolio[]) this.portfolioList = new MatTableDataSource(l ...

JavaScript prototype error: caught TypeError - attempting to call undefined function

I am facing challenges while attempting to create a Factory in AngularJS. I have moved the code from the controller to the factory and made a few adjustments for it to function properly. Here is the error that I am encountering: "El objeto no acepta la p ...

Leveraging the information received from the server within an Angular ngRepeat directive

I have been attempting to retrieve data from the server using the $http service in angular.js and then utilize that data in my template with the ng-repeat directive. However, I am facing an issue where the fetched data is not being displayed properly, and ...

Installing npm displays the command for the successfully installed module, yet no new files are generated

After adding rx-angular to my npm package and successfully installing it locally, I encountered some issues when trying to release it to production. It seemed to partially work but not entirely, leading to confusion due to errors that prompted me to manual ...

Attempting to run the command "npx typescript --init" resulted in an error message stating "npm ERR! could not determine executable to run."

What could be the reason behind the error message npm ERR! could not determine executable to run? Currently, I am attempting to set up a basic Node.js application using TypeScript and Yarn. Yarn is a tool that I am not very familiar with. These are the c ...

Exploring unit tests: Customizing an NGRX selector generated by entityAdapter.getSelectors()

Let's imagine a scenario where our application includes a books page. We are utilizing the following technologies: Angular, NGRX, jest. To provide some context, here are a few lines of code: The interfaces for the state of the books page: export int ...

Utilizing shared enums in Angular services

My services contain an enum that I need to share with another service's method. How can I pass this enum as a parameter effectively? home.factory('myService', ['$dialogs', '$resource', function ($dialogs, $resource) { ...

Displaying the standard index.html page when implementing Angular HTML5mode with Servicestack on the server side

I am brand new to ServiceStack and Angular, so I apologize if this explanation is a bit lengthy. After reading up on the topic at this Stack Overflow post, I'm hoping to configure my api service to be accessible from the root of my domain - in other ...

Tips for fixing the $injector problem in AngularJS

Recently, I started learning AngularJS and attempted to build a simple web page based on some tutorials. The page consists of two parts: one for user input using HTML and the other with JavaScript containing an if-else statement. However, I kept encounteri ...

What could be causing the issue with my dependency injection in my Angular application?

Let's get started angular.module('app', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute' ]) This is my simple factory. Nothing fancy here angular.module('app') .factory(&apos ...

What is the process of encapsulating a callback function within another callback function and invoking it from there?

Here is the code snippet I am working with: var me = this; gapi.auth.authorize({ client_id: client, scope: scope, immediate: true }, function (authResult: any) { if (authResult && !authResult.error) { me ...

Angular Datatables - Equivalent function for fnInfoCallback

Scenario using Angular Datatables In my previous experience with jQuery, I was able to accomplish the functionality shown in the images below: https://i.sstatic.net/VoT2A.png Each Tab displayed a datatable, with the count of filtered records shown next ...

Check if the input values are already in the array and if not, then add

Within my React application, I am displaying an Array and each entry in the Array is accompanied by an input element. These input elements are assigned a name based on the entry's ID, allowing users to enter values. To handle the changes in these inp ...