Leverage an array of objects as the model within a child Angular component, and ensure to monitor any

I have a component that showcases a lineup of items (objects). My goal is to develop another component that takes in this lineup as its model (or parameter) and generates an interactive dashboard with this information. For instance, if I have a list of products along with their respective quantities and prices per unit, I aim to showcase the total price on the child component.

Upon creating the component and passing the list to the child, the total price is accurately displayed. However, whenever new items are added to the list or when modifications are made to the quantity/price of an item within the list, my child component fails to refresh itself.

I've attempted utilizing ControlValueAccessor and OnChanges

Parent Component Code:

<result [(ngModel)]="productList" [test]="armorList"></result>

Child Component Code - I acknowledge that employing both model and input may not be the right approach, but I experimented with both methods, uncertain which one would be more suitable.

import { Component, Input, OnChanges, Output, EventEmitter, forwardRef, SimpleChanges } from "@angular/core";
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
import { Armor, Material } from "../armor-list.component";
import * as _ from "lodash";


@Component({
    selector: 'result',
    templateUrl: './result.component.html',
    styleUrls: ['./result.component.css'],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => ResultComponent),
            multi: true
        }
    ]
})
export class ResultComponent implements ControlValueAccessor, OnChanges {

    @Input() test: Product[];

    ngOnChanges(changes: SimpleChanges): void {
        console.log(changes);
    }

    writeValue(obj: any): void {
        if (obj !== undefined && obj !== null) {
           //logic to calculate the price
        }
    }
    registerOnChange(fn: any): void {
    }
    
    registerOnTouched(fn: any): void {
    }
}

Appreciate your help!

Answer №1

Angular watches changes in arrays and objects based on their references, not their values. When a new item is added to an array, the reference remains the same.

In order for Angular to detect changes in an array, you have two options:

  1. Utilize the ngDoCheck lifecycle hook. Refer to https://angular.io/guide/lifecycle-hooks for more information.
  2. Use the slice method on the input array. Whenever items are added to the array, modify the input array by using let input = originalArray.slice(0). This will create a new reference address that Angular can recognize.

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

Having issues with Angular CLI functionality

Recently, I have been diving into learning Angular 4. To start off, I installed Node.js and executed the following commands in the Node.js command prompt: npm install -g typescript npm install -g @angular/<a href="/cdn-cgi/l/email-protection" class="__ ...

Is it possible to utilize CreateSpyObj to generate a spy for every method within a given class?

I am in the process of creating unit tests for my Angular application and I am exploring the usage of spies. Currently, for each service utilized by my component, I find myself writing code similar to the following: let fakeMyService = jasmine.createSpyO ...

How can I create an Array of objects that implement an interface? Here's an example: myData: Array<myInterface> = []; However, I encountered an issue where the error message "Property 'xxxxxx' does not exist on type 'myInterface[]'" appears

Currently, I am in the process of defining an interface for an array of objects. My goal is to set the initial value within the component as an empty array. Within a file, I have created the following interface: export interface myInterface{ "pictur ...

Unable to see Next.js page in the browser window

I have set up a next.js project with App Router and my file structure under the app folder looks like this: *some other files* . . user | [id] | | page.tsx | @users | | page.tsx | layout.tsx | page.tsx I am ...

Why does the sticky navbar not display anything on localhost:4200 in Angular, but works perfectly when placed in a regular HTML file?

I'm encountering an issue while trying to create a webpage in Angular 6. The content displays correctly when I write the code in NOTEPAD as normal HTML, but it doesn't work as expected when implemented in Angular. I am new to Angular and struggli ...

I am currently making use of the Material UI accordion component and I would prefer for it to not collapse unless I specifically click on the expandIcon

I have been utilizing the Material UI accordion component and am currently struggling to find a solution that prevents the panel from collapsing when it is clicked. Ideally, I would like to manage the opening and closing of the panel solely through click ...

Cannot find property '' within type 'never'. (Using TypeScript useState with mapped JSON data from a server)

Currently, I am following a tutorial on using React with Material-UI and decided to add TypeScript into the mix. If you're interested, here is the link: Net ninja MUI The file Notes.tsx contains the code for fetching data from a JSON server and then ...

Angular FormGroup's setValue method fails to accept specified string value

I've run into a peculiar issue recently. I'm trying to assign a value to a form controller in Angular this.form.controls['WhateverKeyIS'].setValue('ABC'); The above code works fine, but when I try to set a different value thi ...

Ways to initiate a fresh API request while utilizing httpClient and shareReplay

I have implemented a configuration to share the replay of my httpClient request among multiple components. Here is the setup: apicaller.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http& ...

ability to reach the sub-element dictionaries in typescript

class ProvinciaComponent extends CatalogoGenerico implements OnInit, AfterViewInit { page: Page = new Page({sort: {field: 'description', dir: 'asc'}}); dataSource: ProvinciaDataSource; columns = ['codprovi ...

What could be the reason for my button not activating my JavaScript function?

I am encountering an issue with my form-validation sample. When I click the submit button, it should display an alert message but it is not working as expected. Here is a link to my sample: sample link I would greatly appreciate any assistance in res ...

Making an Http Get request in Angular 2 by passing a JSON object

How can I make an HTTP GET request and send a JSON object along with it? Here is the JSON object: {{firstname:"Peter", lastname:"Test"} I want to pass this object in the HTTP request to receive a list of matched persons. Is this possible? The example o ...

rxjs subscriptions in Angular

When setting up a subscription in Angular, I am declaring it as follows: counterSubscription: Subscription However, an error is being thrown stating: Property 'counterSubscription' has no initializer and is not definitely assigned in the const ...

Master the Art of Scrolling Lists in Ionic 2

I am currently using Ionic2 for my project. One of the challenges I'm facing is scrolling to the top of a list when a specific event, called messageSend, occurs. Let me show you the code for this: <ion-content padding class="messages-page-conten ...

Solidjs: Implementing a Map in createStore does not trigger updates upon changes

As a beginner in solidjs, I might have missed something important. In the code snippet below, I am trying to understand an issue: const [state, setState] = createStore({ items: new Map() }); // e.g. Map<number, string> In a component, suppose I want ...

Make sure to add the .npmrc file when setting up a fresh Angular project

Currently, I am in the process of developing a command line application with node.js. This specific application is designed to utilize the ng new command from angular CLI. During the creation of a new angular project, dependencies are automatically install ...

What is the method for assigning a value to an attribute in HTML?

Is there a way to assign a function's value to an HTML attribute? For example, setting the attribute value to the value returned by the function foo. foo () : string { return "bar"; } I attempted the following without any success. <input type="b ...

The test session failed to launch due to an error in initializing the "@wdio/cucumber-framework" module. Error message: [ERR_PACKAGE_PATH_NOT_EXPORTED]

I added @wdio/cli to my project using the command 'npm i --save-dev @wdio\cli'. Next, I ran 'npx wdio init' and chose 'cucumber', 'selenium-standalone-service', 'typescript', 'allure' along w ...

What is the best approach to implement a recursive intersection while keeping refactoring in consideration?

I'm currently in the process of refactoring this code snippet to allow for the reuse of the same middleware logic on multiple pages in a type-safe manner. However, I am encountering difficulties when trying to write a typesafe recursive type that can ...

I'm looking to enhance my Angular app by implementing a submenu that features various tabs

Currently, I am following a tutorial available at this link to achieve my desired outcome. However, I am facing some challenges because my tabs are not located in the root component. In my scenario, I have a contract with certain properties that I want to ...