Identify alterations in the elements of the provided array

Currently, I am facing an issue with detecting changes in Angular component Input variables. The specific variable I am dealing with is an array of objects where I need to pinpoint which object is changing and which property within that object is being modified. This detection is crucial as it dictates the behavior of form controls within a child component controlled by a parent component.

I have experimented with several solutions including:

Detect changes in objects inside array in Angular2

constructor(private differs: KeyValueDiffers) {
}

ngOnInit() {
  this.objDiffer = {};
  this.list.forEach((elt) => {
    this.objDiffer[elt] = this.differs.find(elt).create(null);
  });
}

Despite my efforts, the function .create necessitates a TrackByFunction parameter, making it impossible to assign this.objDiffer[elt] due to its nature as an object rather than a list of objects.

Detect changes in objects inside array in Angular2

 private objDiffers: Array<KeyValueDiffer<string, any>>;

  constructor(
    private differs: KeyValueDiffers) {
    this.itemGroups = new Array<ItemGroup>();
    this.differ = this.differs.find(this.itemGroups).create();
  }

  public ngOnInit(): void {
    this.objDiffers = new Array<KeyValueDiffer<string, any>>();
    this.itemGroups.forEach((itemGroup, index) => {
      this.objDiffers[index] = this.differs.find(itemGroup).create();
    });
  }

ngDoCheck(): void {
    this.itemGroups.forEach((itemGroup, index) => {
      const objDiffer = this.objDiffers[index];
      const objChanges = objDiffer.diff(itemGroup);
      if (objChanges) {
        objChanges.forEachChangedItem((changedItem) => {
          console.log(changedItem.key);
        });
      }
    });
  }

Although this method helps identify the changed value, it fails to provide information about the specific object that experienced the change.

export class ArrayWatchDemoComponent implements DoCheck {

  @Input() datasource: Array&lt;any&gt; = [];

  differ: any;

  constructor(differs: IterableDiffers) {
     this.differ = differs.find([]).create(null);
   }

  ngDoCheck() {
    const change = this.differ.diff(this.datasource);
    console.log(change);
  }

This approach only outputs null values in the console, even though it responds to property changes within the input object array. Utilizing forEachAddedItem or forEachRemovedItem did not resolve this limitation.

@Input() empArray: Employee[];
empDifferMap = new Map<number, any>();
empMap = new Map<number, Employee>();
arrayDiffer: any;
constructor(private kvDiffers: KeyValueDiffers) {}
ngOnInit() {
    this.empArray.forEach(emp => {
      this.empDifferMap[emp.id] = this.kvDiffers.find(emp).create();
      this.empMap[emp.id] = emp;
    })
}
ngDoCheck() {
    for (let [key, empDiffer] of this.empDifferMap) {
      let empChanges = empDiffer.diff(this.empMap.get(key));
      if (empChanges) {
        empChanges.forEachChangedItem(record => {
          console.log('Previous value: ' + record.previousValue);
          console.log('Current value: ' + record.currentValue);
        });
      }
    }
} 

My most recent attempt involved implementing the above code but encountered the following error:

"ERROR in src/app/forms/dynamic-form/dynamic-form.component.ts(39,34): error TS2569: Type 'Map' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators."

I also tried resetting the array content like so:

//this.list = [{foo: true}];
this.list = [];
this.list = [{foo: false}];

However, this proved to be a cumbersome solution that caused flickering elements in the child component.

In summary, my objective is for the child component to effectively detect changes within an object located in an input array provided by the parent component. Unfortunately, the current implementation falls short in achieving this goal

Answer №1

If you're looking for a powerful and effective way to handle form changes, I suggest using FormArray within Angular Reactive Forms. It's a great tool for detecting and managing changes efficiently. Check out this helpful guide to get started with FormArray: FormArray starter

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

Error message: Failure to define class methods when exporting the class from a file

In my project, I have defined a class called BinarySearchTree in a file named a.js. This class has been exported and then imported into another file where it is used as the parent class for a different class called Traversal. However, I encountered an issu ...

I'm looking to learn how to implement the delete method in an API using TypeScript. Can anyone help me out

I am seeking guidance on utilizing 'axios' within 'nuxt.js'. I have experimented with sample data, and I am particularly interested in learning how to utilize the 'axios' method within 'nuxt.js' using TypeScript. T ...

Error: Jest + Typescript does not recognize the "describe" function

When setting up Jest with ts-jest, I encountered the error "ReferenceError: describe is not defined" during runtime. Check out this minimal example for more information: https://github.com/PFight/jest-ts-describe-not-defined-problem I'm not sure what ...

How to Decode JSON Data in Angular 2/4 with the Help of HttpClientModule

I am receiving this JSON structure from my asp.net core API: { "contentType": null, "serializerSettings": null, "statusCode": null, "value": { "productName": "Test", "shortDescription": "Test 123", "imageUri": "https://bla.com/bla", ...

The performance of the Express.js interface is currently lacking

Questions for using Express.js: Code: app.use(A) app.use(B) { const isCurlR = app.use(function (req, res, next) { next() }) isCurlR.get('/getLatest', (req, res) => {}) } { const isNotCurlR = app.use(function (req, re ...

Tips for sorting the echarts line chart on a weekly basis using angular

How can I filter the echarts line chart by week in Angular? Currently, it displays all records like 2019-10-27 10:15:00, 2019-10-27 10:15:30, 2019-10-27 10:16:00, 2019-10-27 10:19:00. Instead, it should only show dates like 2019-10-27. For example, if ther ...

Break down the provided Array type into distinct new types

If we have a specific type defined as: type Tuple = [name: string, age: number, address: string]; and we are interested in creating a new type without the first element, like this: type NewTuple = [age: number, address: string]; Is there a way to achieve ...

What is the best way to send email using angular from server/cPanel?

Currently, I am working on an Angular application that includes a contact form. Once a user submits the form, I would like to automate the process of sending an email to myself with the information provided by the user. Can I send the email directly from ...

Cannot execute npm packages installed globally on Windows 10 machine

After installing typescript and nodemon on my Windows 10 machine using the typical npm install -g [package-name] command, I encountered a problem. When attempting to run them through the terminal, an application selector window would open prompting me to c ...

Error: Unable to locate loading.gif file within the Angular library

In my current setup, I have a monorepo that includes a standard Angular application and an Angular workspace with a library at the same level as the app. After configuring the main app to recognize the library, I am able to use the components without any ...

The ReactJS template with Typescript is throwing an error stating that the property useContext does not exist on type

After creating a react-app using yarn create react-app app-name --template typescript, I have the following code snippets to share: AuthProvider.tsx import { createContext, useState } from "react"; const AuthContext = createContext({ }); ex ...

Understanding Type Inheritance in TypeScript: Assigning a variable of a parent type to a variable of a child type

A scenario involves creating two distinct types: export class GenericType { public id: string; public property: string; public name: string; } export class SpecificType extends GenericType { public value: string; } Let's say we have two vari ...

The TypeScript variable is automatically assigned the type 'any' since it does not contain a specified type annotation

Issue: The variable 'environment' is implicitly assigned the type 'any' because it lacks a specific type annotation and is referenced within its own initialization code. Code Snippet: export const environment = { production: fals ...

Using Typescript, the type T or a function that returns T can be utilized in various scenarios

You can check out a demonstration on this interactive platform. In creating a simple generic type that represents either a variable or a function returning a variable, there was an issue with the typical typeof arg === 'function' check. The erro ...

Removing a nested data object in Angular with NGXS

I have successfully implemented the get and delete functions for posts in my Angular app. However, I am facing issues when trying to delete a comment within a post using NGXS. How can I access the comment inside the post in order to delete it? Here's ...

The current error message is: "ReferenceError: spyOnProperty is not defined

it('needs to be able to update treatment instructions in the user interface', async(() => { const spy = spyOnProperty(appService.treatmentInstruction, 'next', 'get').and.returnValue(treatmentInst); component ...

Can the base href in Angular be dynamically changed during runtime?

Within my single Angular application, I have set the base-href to /a/b/. This means that in my dist folder, there is an HTML file with <base href="/a/b/">. As a result, the browser recognizes that an image link like assets/images/logo.png can be foun ...

How can I identify when the payment form in Stripe Elements has finished loading?

When implementing a payment form using Stripe elements, I have noticed that there is sometimes a delay of 5-10 seconds for the form to load completely. Is there a way to detect when the form has finished loading so that I can display a loading animation or ...

Center the logo within the NavBar

I'm having trouble centering the logo in my navbar and getting elements to spread out from the logo on both sides. I also want to position the buttons at the end of the navigation bar. Here's the desired layout In my code, I attempted to create ...

What is the best way to assign a class to a clicked element and remove it from the previous one?

Currently, I am utilizing Angular to control the visibility of different divs using the ngIf feature. Below is an example of what I have implemented: .html <div class="boxes"> <div class="box" (click)="tabToggle(1)">box1</div> <div c ...