Exploring the Difference Between $onChanges and $onInit in Angular Components

What sets apart the use of Controller1 compared to Controller2?

angular.module('app', [])
.component('foo', {
    templateUrl: 'foo.html',
    bindings: {
        user: '<',
    },
    controller: Controller1, //Or Controller2
});

function Controller1(){
    this.$onInit = function(){
      this.user = angular.copy(this.user);
    };

    this.$onChanges = function(changes){
      if(changes.user && !changes.user.isFirstChange()){
        this.user = angular.copy(changes.user.currentValue);
      }
    };
}


function Controller2(){
    this.$onChanges = function(changes){
      if(changes.user){
        this.user = angular.copy(changes.user.currentValue);
      }
    };
}

Is it necessary to use $onInit when achieving the same result is possible with $onChanges and in fewer lines of code?

Would using $onChanges or $onInit be more suitable for specific types of initialization tasks?

Answer №1

Initialization Method

Executed on each controller after all the controllers within an element have been created and had their bindings set (and prior to the pre & post linking functions for the directives within that element). This is an ideal location to include initialization code for your controller.

Changes Tracker

The $onChanges lifecycle hook is triggered for a couple of reasons. Firstly, during component initialization, it receives the initial changes Object in real-time, allowing us to access our data promptly. Secondly, it is called only when modifications occur to '<' (one-way data binding) and '@' (for evaluated DOM attribute values) that are connected from the parent component. Once the $onChanges method is invoked, you will receive a specialized changes Object which can be utilized further, as discussed in the following sections.

The key practical distinction is that $onInit is solely executed upon directive initialization, while $onChanges is triggered both during initialization and whenever alterations are made to < and @ variables.

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 hexagons configuration for tsParticles is experiencing technical difficulties

I'm struggling to implement the tsParticles library (specifically using react-tsparticles) in combination with the latest version of Next.js. However, when I try to use the particle.json file and bind it to the <Particles/> component, the partic ...

Implementing a pop-up notification at the center of the display for empty fields

I am currently working on a task that requires me to display a pop-up message at the top-middle of the screen stating "please fill in all fields before submitting". This custom box should be stylable using CSS. Although the solution seems simple, I am str ...

Is there a way to incorporate an animated element within the track of my circular progress bar?

My circular progress bar features two paths, with one path increasing in length as data is received, eventually turning the entire circle red. Here is the SVG HTML code: <path d="M 50,50 m 0,-47 a 47,47 0 1 1 0,94 a 47,47 0 1 1 0,-94" stroke="#A9B0B7" ...

Error encountered in Webpack configuration while using html-webpack-plugin to generate index.html file

I've been experimenting with webpack to bundle project JS files. My goal is to generate an index.html file under the output dist folder using webpack. To achieve this, I followed the instructions provided in the webpack documentation and installed "h ...

Navigation that sticks and changes upon hovering over div elements

Just delving into the world of jQuery and JS, so I appreciate your patience:) Currently, I have a sticky navigation bar positioned at the top of my webpage that links to different sections of content below. I am looking to create an effect where the corr ...

Execute a PHP script to modify a section of a PHP file

I successfully implemented a piece of code into a PHP file by manually searching for the right section and inserting it. Now, I am looking to automate this process with an install script for my code. The ideal installation script would: 1. Copy the exist ...

Transform Json data from JavaScript format to a format that PHP can understand

I have a collection of json files that I need to parse and extract information from in order to store it in a database using PHP. The issue I'm encountering is that these json keys do not have quotes around them, like: [{f:{v:11,ib:5,gh:"res",bfr:7, ...

Looking to retrieve HTML elements based on their inner text with queryselectors?

I am looking to extract all the HTML divs that contain specific HTML elements with innerText = ' * ' and save them in an array using Typescript. If I come across a span element with the innerText= ' * ', I want to add the parent div to ...

How can I identify and return false if all the digits from 0 to 9 are matching with other characters in a string?

In my current project, I am focusing on filtering out numerical values only. I have implemented a phone mask using JavaScript on the front end to filter user input to a specific format such as (000)000-000, which includes numbers ranging from [2-9] and [0- ...

Exploring the world of Node.js, JSON, SQL, and database tables

Hello everyone, I have been working on a project using Node.js and Express framework. My current goal is to create a client-side page that allows users to input form data into a MySQL database. I have managed to successfully insert and retrieve data from ...

Is there a way to directly display all the content in pagination format without a print preview option?

I have been tasked with implementing a feature that involves displaying content using pagination and allowing users to print all the content at once with a single click on a print button. However, I am currently experiencing an issue where clicking the pri ...

To trigger the action of any button in Ionic/Angular, I need to double-click

I am encountering an issue with an app that I developed using the Ionic framework. While the app works perfectly on Android devices, I am facing a peculiar situation on iOS. Every time I click a button in the Simulator or on an actual iOS device, I have t ...

Tips for including a JSON file within the utils directory of a Node.js project

I have a JavaScript file located in the utils folder of my Node.js project. This JS file is responsible for retrieving data from a database. However, at the moment, I only have mock data stored in a local JSON file. Now, I need to figure out how to load th ...

Tips for ensuring that the "this" in React ES6 static method is bound to the lexical scope

Currently in React with ES6 via babel, my goal is to develop a static method that can update the state of the Component it belongs to by accepting an object as an argument. However, I'm facing an issue where "this" is not bound to the lexical scope. ...

The input tag contains an empty Request.Form

My issue lies in using Request.Form to retrieve text from an input field, as the value always ends up being empty. My goal is to extract the text value from the input tag and use it to query my database. I have attempted to write to an ASP TextBox but enco ...

Successful Ajax response notification

I am new to using ajax and I want to implement a .post method with an if condition to notify the user of its success or failure. Here is my code for .post: $.post("ajaxRegistering.php",{ name: name, lastname: lastname, ...

Successfully running npm update on a Mac seemed to have updated the package, however, the

I needed to upgrade my npm version using the following command: npm install npm@latest -g After running the above command, I encountered the following output: /Users/ariful.haque/.npm-global/bin/npm -> /Users/ariful.haque/.npm-global/lib/node_modules ...

What is the best way to create a button that can cycle through various divs?

Suppose I want to create a scroll button that can navigate through multiple div elements. Here is an example code snippet: <div id="1"></div> <div id="2"></div> <div id="3"></div> <div id="4"></div> <div ...

Re-calculating with Jquery when input is updated

I am looking for guidance on how to make the calculator recalculate based on a change in the #calcTotal input field. I have successfully calculated all fields and managed to update the #cwac field when one of the values before it changes. Here is the HTML ...

Can you explain the purpose of using the 'apply' method in this particular implementation of memoization in JavaScript?

_.memoize = function(func) { var cache = []; return function(n){ if(cache[n]){ return cache[n]; } cache[n] = func.apply(this,arguments); return cache[n]; } }; I'm curious about the usage of 'this' in func.appl ...