Angular 6 - Issue with ngOnChanges not triggering for nested arrays

Within my code, there is a toSpecialities object containing two arrays: specialitiesOptions and specialities. This object is passed from a parent component to a child component.

this.toSpecialities = { specialitiesOptions: specialities, specialities: this.exerciseFramework.specialities };
<ef-specialties [data]="toSpecialities"></ef-specialties>

Within the child component, I utilized the ngOnChanges function to monitor any changes in the object.

@Component({
    selector: 'ef-specialties'
})
export class SpecialtiesComponent implements OnChanges {

    @Input()
    public data: any;

    constructor() { }

    ngOnChanges(changes: SimpleChanges) {
        if (changes["data"] && changes["data"].currentValue) {
          console.log(changes["data"]);
        }
    }

}

However, when attempting to update the specialities, the change in the toSpecialities object within the child component is not detected.

this.toSpecialities.specialities = this.array.specialities;

Answer №1

The reason for this behavior is that ngOnChanges only fires when the object reference changes for properties decorated with @Input. It will be activated if you modify the input value for a simple type property (string, boolean, number), but it won't trigger if you change a property of an object.

If you want to ensure that ngOnChanges gets triggered, you can follow this approach:

this.toSpecialities = {...this.toSpecialities, 
   specialities: this.array.specialities};

This code snippet creates a copy of this.toSpecialities and modifies the value of its specialities property. Modifying the value of toSpecialities will subsequently trigger the ngOnChanges method.

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

Is there a way to dynamically adjust the size of an image in NodeJS utilizing Sharp, when only provided with a URL, employing async/await, and ensuring no local duplicate is

In my current work environment, the only image processing library available is NodeJS's Sharp for scaling images. It has been reliable due to its pipe-based nature, but now I have been given the task of converting it to TypeScript and utilizing Async/ ...

Error TS2307 - Module 'lodash' not found during build process

Latest Update I must apologize for the confusion in my previous explanation of the issue. The errors I encountered were not during the compilation of the Angular application via Gulp, but rather in the Visual Studio 'Errors List'. Fortunately, I ...

How can I send form data along with images from Angular to Node.js via an http post request?

When designing this template, I am requesting product information and an image to be stored. <input type="hidden" formControlName="_id"> <input type="file" formControlName="ProductImage" #ProductImage> <mat-form-field> <input for ...

Navigate to the login page in Angular 2

Initially, the template login (login.component) needs to be called first. Once the login is complete, then app.component will be loaded. Is it possible to achieve this? And if so, how can I do it? Edited Question: I am already using CanActivate. Apologi ...

No data found on Angular TypeScript page with an empty array

Incorporated a function called 'getQuestionsWithInterviewId' to populate my 'Questions' string, but it appears empty when I attempt to call it within the ngOnInit and ngAfterContentInit methods and log the result in the console. import ...

Error encountered when trying to match routes in two separate Angular applications within an Express app: "Cannot find any routes that match

Greetings (please pardon any language errors as English is not my first language) Like many others, I have an Angular app running in Express and decided to create separate Angular apps for the admin and users (mainly because the navigation bar was becomin ...

You are unable to call upon an object that may be of type 'undefined' in typescript

Among all the other inquiries on this topic, my issue lies with the typescript compiler seeming perplexed due to the following code snippet: if(typeof this[method] === "function"){ await this[method](req,res,next) } The error message I am en ...

What is the method for utilizing an alias at the top within a subquery?

Is it possible to use an alias from the top query in a subquery? I am currently encountering an error with 'artc'. let myQuery = this.articles.createQueryBuilder('artc') .select(['artc.title']) .addSelect(qb => ...

Executing a function on a child component solely based on the parent component's observable in Angular4

"To put it simply: I want to make only one HTTP request and share that data with all components. The challenge is that the other components start running before I receive the response from the initial HTTP request. All components are just extracting pieces ...

How to create a separate modal component in Angular without relying on ng-modal

I am facing an issue with ComponentB, which contains HTML code for a Bootstrap modal. I want to open ComponentB from ComponentA. Although the component is getting loaded when inspected, the popup modal does not appear on the UI. <app-root> <ap ...

Receiving an `Invalid module name in augmentation` error is a common issue when using the DefaultTheme in Material

After following the guidelines outlined in the migration documentation (v4 to v5), I have implemented the changes in my theme: import { createTheme, Theme } from '@mui/material/styles' import { grey } from '@mui/material/colors' declar ...

Execute the function upon clicking

When I click on an icon, I want it to blink. This is the code in my typescript file: onBlink() { this.action = true; setTimeout(() => { this.action = false; }, 1000) return this.action }; Here is how the action is declared in my ...

NX - A comprehensive UI library featuring Storybook integration and individually exported components

As I delve into the world of Nx with Angular (fairly new to both), I am on a quest to create a component library that serves two main purposes: Capable of running Storybook Allowing components to be imported individually, rather than having to drag in the ...

Updating a Record in Angularfire2

So, I'm fairly new to using Angular and I'm currently working on a small web application. After setting up angularfire 2, I was able to successfully create a new list entry using Push(). For example, let's say my list (users) only contains ...

Designing a TypeScript class with unique properties and attributes

I have an idea for creating a versatile class named Model. Here's what I have in mind: export class Model { _required_fields: Array<string> = []; _optional_fields?: Array<string> = []; constructor(params: Dictionary<string& ...

What sets apart the various download options for Typescript, such as npm, NuGet, and Marketplace?

While working in VS Pro, I am a beginner developer in TypeScript (as well as React and Node...). I am focused on truly understanding how these technologies integrate and function together, rather than simply copying commands and code snippets into files. ...

What is the method for retrieving data from a node in Firebase Realtime Database using TypeScript cloud functions, without relying on the onCreate trigger?

Being a beginner with Firebase and TypeScript, I have been struggling to retrieve values from a reference other than the triggered value. Despite finding answers in JavaScript, I am working on writing functions using TypeScript for real-time database for A ...

Encountering an issue while trying to integrate custom commands using the addCommand function in WebDriverIO

When using the addCommand function to add a new command, I encountered an error message that states: [ts] Property 'WaitForElementsAmount' does not exist on type 'Client<void>'. Here is an example of the code snippet I used: br ...

Angular 2's version of the code above

Struggling to transition this code from angularjs to angular 2, appreciate any assistance if (settings != null && settings.checkSubscriptionForVip === true) { return this.user.hasVipAccess().then(function(hasVipAccess) { hasV ...

The module './installers/setupEvents' could not be located within Electron-Winstaller

After encountering an error while attempting to package my Angular app on Windows 10, I'm looking for help in resolving the issue: https://i.stack.imgur.com/yByZf.jpg The command I am using is: "package-win": "electron-packager . qlocktwo-app --ove ...