Identifying the specific @Input that has changed in ngOnChanges

I am currently utilizing Angular 2.

At the moment, I have two @input variables named aa and bb. My objective is:

  1. When aa changes, perform a specific action.
  2. When bb changes, execute a different action.

How can I identify which @Input has changed within the ngOnChanges method? Thank you

@Input() aa;
@Input() bb;

ngOnChanges(changes: { [propName: string]: SimpleChange }) {
    // if aa changes, do something
    // if bb changes, do other thing
}

Answer №1

One possible solution could be implemented in the following manner

ngOnChanges(changes: { [propName: string]: SimpleChange }) {
  if( changes['aa'] && changes['aa'].previousValue != changes['aa'].currentValue ) {
    // aa property has changed
  }
  if( changes['bb'] && changes['bb'].previousValue != changes['bb'].currentValue ) {
    // bb property has changed
  }
}

It is surprising to see the unchanged properties being defined. According to the cookbook, I would anticipate only the changed properties to be defined.

Link to further information on parent to child communication with ngOnChanges

If the above approach seems too verbose, an alternative method using setters can also be tried:

_aa: string;
_bb: string;

@Input() set aa(value: string) {
  this._aa = value;
  // perform actions when 'aa' changes
}

@Input() set bb(value: string) {
  this._bb = value;
  // perform actions when 'bb' changes
}

Link to more details on parent to child communication using setter methods

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

Checking constructor arguments and code style issues

I need to ensure that the constructor parameter is validated correctly when an instance of a class is created. The parameter must be an object that contains exactly all the properties, with the appropriate types as specified in the class definition. If t ...

Destructuring an array of strings for use as parameters

Hey guys, I'm working with an array of keys here Example 1: let keyArray = ['x', 'y', 'z'] I'm trying to find a way to use these keys as parameters without repeating them multiple times. Do you have any suggestions ...

What are the best ways to utilize .svg images for native script splash screens, backgrounds, icons, and buttons?

I am interested in replacing the .png files I previously used for my native script android app with .svg files. My goal is to utilize svg images for splash screens, backgrounds, icons, and buttons. Thank you! ...

Need help inserting an image into the div when the ngif condition is true, and when the ngif condition is false

Essentially, I have a situation where I am using an *ngIf condition on a div that also contains an image. This is for a login page where I need to display different versions based on the type of user. However, I'm facing an issue where the image does ...

Is there a way to render a component without having to render AppComponent constantly?

I am looking to display two components (AppComponent and UserComponent) without constantly displaying AppComponent. Here's how my code is structured: app.routing.module.ts const routes: Routes = [ { path: '', component: AppComponent ...

angular change digits to Persian script

I am trying to convert English numbers to Persian numbers in angular 4: persianNumbers = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"]; engli ...

Error in Angular SSR: Build failed due to project reference without "composite" setting set to true

Currently facing an issue while developing an Angular App with SSR. When using npm run build:ssr, the following errors are displayed: ERROR in [...]/tsconfig.json [tsl] ERROR TS6306: Referenced project '[...]/tsconfig.app.json' must have se ...

Enrolling a new plugin into a software repository

I have 5 unique classes: ConfigManager ForestGenerator TreeCreator NodeModifier CustomPlugin My goal is to create an npm module using TypeScript that incorporates these classes. The main feature I want to implement is within the ConfigManager clas ...

Issue with rejecting a promise within a callback function in Ionic 3

Within my Ionic 3 app, I developed a function to retrieve a user's location based on their latitude and longitude coordinates. This function also verifies if the user has location settings enabled. If not, it prompts the user to switch on their locati ...

When attempting to register a custom Gamepad class using GamepadEvent, the conversion of the value to 'Gamepad' has failed

I have been working on developing a virtual controller in the form of a Gamepad class and registering it. Currently, my implementation is essentially a duplicate of the existing Gamepad class: class CustomController { readonly axes: ReadonlyArray<nu ...

Verifying the format of an object received from an HTTP service using a TypeScript interface

Ensuring that the structure of the http JSON response aligns with a typescript interface/type is crucial for our javascript integration tests against the backend. Take, for example, our CurrentUser interface: export interface CurrentUser { id: number; ...

Understanding the concept of inconsistent return points in Typescript: What implications does it carry?

I am currently working on converting a NodeJs JavaScript code to TypeScript. The code snippet below shows how I save uploaded files using JavaScript and now I'm encountering an error when trying to do the same in TypeScript. The error message says "Fu ...

Eliminate the "email address" input field from Stripe checkout in Angular 2

I am currently using Angular 2 for my project and need some help. Is there a way to remove the email address field from Stripe checkout? https://i.stack.imgur.com/auf6C.png Thank you in advance! ...

What is the best way to incorporate an automatic scroll to the following section on a single page website

My goal is to implement a feature that enables automatic scrolling between sections as the user scrolls up or down. The smooth transition should occur when the user reaches halfway through each section, seamlessly moving to the next screen on the same page ...

"TypeScript function returning a boolean value upon completion of a resolved promise

When working on a promise that returns a boolean in TypeScript, I encountered an error message that says: A 'get' accessor must return a value. The code snippet causing the issue is as follows: get tokenValid(): boolean { // Check if curre ...

Differences between Pipe and Tap when working with ngxsWhen working with

While experimenting with pipe and subscribe methods, I encountered an issue. When using pipe with tap, nothing gets logged in the console. However, when I switch to using subscribe, it works perfectly. Can you help me figure out what I'm doing wrong? ...

Updating the state in a different component using React and Typescript

The Stackblitz example can be found here I'm attempting to update the useState in one component from another component. Although it seems to work here, it's not functioning properly in my actual application. Here is a snippet of the app.tsx co ...

A destructured object with a Typescript interface

While working on a React / TypeScript project, I encountered an error involving destructuring an object. The issue arises when I try to destructure notificationData within the publish function. An error message stating "Property 'messages' does ...

Angular ngx-leaflet automatically adjusts to focus on a specific region when loading data

Utilizing Angular 6 and ngx-leaflet for my project. I am fetching data from the backend and trying to zoom in on a specific area (in this case India) once the data is loaded onto the map. This is how my HTML appears: <div leaflet style="height: 800px ...

Arrange an array of integers and letters alphabetically in an Angular/Typescript environment

My Sorting Strategy I am attempting to organize an array in the following manner... 1 2 2(a) 2(b) 2(b) #AsimpleName 2(b) #NameWithN 3 4 4(a) ... ... using Angular 2. Snippet of My Code Component this.streetDetailRef = this.afDatabase.list('data/us ...