Angular may struggle to detect changes when it comes to nested components

I encountered a similar issue to mine on Stack Overflow. However, despite following the steps provided in the solution, my implementation is still not working.
Here is the structure of my components:

  • Dashboard
    • ActionButton
    • Milestone
      • Table
    • SupplierSearch
      • Table

I attempted to pass the array selectedRows from Table to Dashboard, and then to ActionButton using CustomEvent and

elRef.nativeElement.dispatchEvent
. However, when I tried to log the data to see if it was successfully passed to any parent component (Dashboard or Milestone) from Dashboard/Milestone/Table, the array did not get passed.

Please note that my code might be messy at the moment because I have been trying to fix this issue for almost a day and have experimented with various solutions. Kindly focus on the way I tried to implement the mentioned solution (CustomEvent and

elRef.nativeElement.dispatchEvent
).

I am truly grateful for the knowledge shared by the Stack Overflow community, so please do not downvote this post if my English is poor or if there are inherent flaws in my problem statement.

Table

import {
  Component,
  ElementRef,
  EventEmitter,
  Input,
  Output,
  TemplateRef,
} from '@angular/core';
import { TableColumnHeader } from './models/table-column-header';

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.scss'],
})
export class TableComponent {
  @Input() rowData;
  @Input() headers: TableColumnHeader[] = [];
  @Input() columnTemplate: TemplateRef<any>;
  @Input() loading: boolean = false;

  @Output() selectedRowsEvent = new EventEmitter<any[]>();

  selectedRows = [];
  constructor(private elRef: ElementRef) {}

  // Rest of the TableComponent JavaScript code...

Milestone

// Milestone component JavaScript code...

Dashboard

// Dashboard component JavaScript code...

ActionButton

// ActionButton component JavaScript code...

Answer №1

Challenges Faced in Passing the Data

  • The changes on the child component were not triggered when passing a complex object
  • As a result, the data got stuck at the dashboard (parent component) and did not reach the child component

https://i.sstatic.net/NRjIa.png

- The workaround is to pass the subscribe object
  • Another reason for the unsuccessful passage:

    We have this view structure:

    • Dashboard
      • ActionButton
      • Milestone
        • Table
      • SupplierSearch
        • Table

    I was attempting to pass from table -> milestone -> dashboard -> actionbutton,

    but I was actually selecting rows on the SupplierSearch view of the table on the UI. Therefore, it never reached the Milestone from the Table.

Solution

  • Pass the array up to the parentmost component (Dashboard) with event emitters

  • Create a Subject$ (observable) to broadcast the complex data to the child component

    A Subject is similar to an Observable but can multicast to many Observers. Subjects are like EventEmitters: they maintain a registry of many listeners. — source rxjs

    Code snippet

    dashboard.ts
    
    selectedRows$ = new Subject<any[]>();
    
    onNotify(rowsEmitted: any[]): void {
        console.log('from Dashboard onNotify ');
        this.selectedRows = rowsEmitted;
        this.selectedRowsCount = rowsEmitted.length;
        console.log(this.selectedRows);
        this.selectedRows$.next(rowsEmitted);
      }
    
    • on notify is the final function in the chain to pass the array up to the parent component
    • Then create an anonymous observer and subscribe (next())
  • Subject selectedRows$ will then be passed to the child component action button

    dashboard.html
    
    <app-action-button [selectedRows]="selectedRows$">
    </app-action-button>
    
  • An anonymous observer and subscriber will be created

    action-button.ts
    
    ngOnInit(): void {
        // this.router.navigate([backUrl]);
        console.log('from action button component ');
        console.log(this.selectedRows);
        this.selectedRows.subscribe((selectedArray) =>
          console.log('from action button ngOnInit: ' + selectedArray)
    );
    
    
    

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

Oops! A mistake was made by passing an incorrect argument to a color function. Make sure to provide a string representation of a color as the argument next time

Encountering an issue with a button react component utilizing the opacify function from the Polished Library The styling is done using styled-components along with a theme passed through ThemeProvider. Upon testing the code, an error is thrown. Also, the ...

Unlock the secrets of extracting video from a livestream and seamlessly transferring it to a local web server without the need

Hey there, I have this link: '' Although it's not a real link, entering it leads to a .m3u8 file for live video streaming. I attempted using this link in my Angular 6 app frontend, but encountered a cross-origin issue as the video is being ...

What are the steps to resolve the DOMException error "Failed to execute 'open' on 'XMLHttpRequest': Invalid URL" in Angular HttpClient when making requests to a third-party server or API?

I am encountering the following issue: DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL while trying to perform a GET request to debounce.com import{HttpClient} from '@angular/common/http'; export {T ...

What is the process for loading data with no input provided?

I have come across a situation where my HTML table is populated with various account numbers. https://i.sstatic.net/qJc2E.png When I input the account number 979545130406, the filter works perfectly fine. https://i.sstatic.net/Y4Rwk.png However, the is ...

The Typescript intellisense feature in VS Code seems to be malfunctioning

While setting up typings for my Node server, the intellisense suddenly stopped working. I checked my tsconfig.json file: { "version": "0.1.0", "command": "tsc", "isShellCommand": true, "args": ["-p", "."], "showOutput": "silent", " ...

Utilizing TypeScript interfaces with additional parameter object members does not result in the anticipated compilation error

Consider the different types listed below: type Person = { id: string; name: string; }; interface PeopleRepository { getPerson(query: { id: string }): Person; } class Repository implements PeopleRepository { getPerson({ id, age }: { id: string; ...

Mastering the utilization of bootstrap-select in TypeScript while ensuring "noImplicitAny" is set to true can be quite the challenge, especially when confronted with the issue of bootstrap-select/index

Hello, I am currently exploring Typescript and attempting to incorporate bootstrap-select into a project that requires "noImplicitAny": true. However, I am encountering an issue while trying to import BootstrapSelect from @types/bootstrap-select. The erro ...

Assign each active class name to the Tab components in React

I'm struggling to figure out how to apply an active class to each tab title so that it can have a distinct style when clicked. I'm looking for solutions on how to achieve this within these components, any help is greatly appreciated. App.tsx imp ...

The module 'AnotherModule' in a different file has unexpectedly imported a value 'Module in file'. Make sure to include a @NgModule annotation to resolve this issue

After struggling with this problem for the past four days, I've exhausted all resources on Stack Overflow and Google. Hopefully, someone here can provide some insight. I have two Angular 11 libraries - one core and the other called components. Compone ...

The process of a ReactJS component's lifecycle is affected when an onClick event triggers a fetch function, causing the state

For the past week, I've been grappling with a coding challenge. My goal is to create a basic Pokedex featuring the original 151 Pokemon. The list of Pokemon should be displayed on the right side of the screen, pulled directly from a .json file copied ...

Encountering an error when using Jest and the envalid library to test a React application: process.exit invoked with code "1"

While testing my React/Typescript application with Jest, I encountered an error. I am utilizing the envalid library to manage my environment variables with types and autocompletion: const ENV = cleanEnv(process.env, { | ^ 6 | R ...

When using the map function, I am receiving an empty item instead of the intended item based on a condition

Need assistance with my Reducer in ngRx. I am trying to create a single item from an item matching an if condition, but only getting an empty item. Can someone please help me out? This is the code for the Reducer: on(rawSignalsActions.changeRangeSchema, ...

Tips for creating a personalized asynchronous Express handler that seamlessly receives specific typed parameters

In my quest to create a unique Express endpoint wrapper, I aim to wrap async functions and handle errors effectively. The current implementation is basic but functional: import type {Request, RequestHandler, Response} from 'express'; type Handle ...

Alert displaying NextJS props

I recently began learning Next.js and have encountered an issue while trying to pass props from a parent component to a child component. The error message I'm seeing is: Type '({ name }: { name: any; }) => JSX.Element' is not assignable ...

Tips for Creating an Array of JSX Elements:

Is there a way to populate an Array with JSX Elements without encountering errors? Consider the following scenario: const arrayOfJsxElements : string[] = []; arrayOfJsxElements.push(<div>hi</div>); However, this approach results in the e ...

Encountering an endless loop within a data rest API in a React application

Currently, I am in the process of learning React and attempting to utilize the Poke API with my application. Unfortunately, I seem to have run into an infinite loop issue and I am feeling quite lost in terms of troubleshooting it. Below is a snippet of my ...

The element's 'nativeElement' property cannot be accessed because it is undefined

I have a scenario where I have a parent component and a child component. I am trying to access the DOM element of the Child component from the Parent component, but I keep encountering an issue with the native element being undefined. export class ChildCom ...

I am facing a problem with the code for my React login page and router

My form page is built in react and typescript, utilizing JWT tokens on the API side. While there are no issues with the container page, I encountered an error on the index.tsx page where the routers are defined: A TypeScript error occurred in C:/Users/yusu ...

Sort through a list of objects by certain properties

I'm currently dealing with two arrays: one contains displayed columns and the other contains objects retrieved from a database, with more attributes than the displayed columns. displayedColumns = ['CompanyName','Ticker', 'Id& ...

Creating dynamic dxi-column with different data types in dxDataGrid

Our team is currently working on an angular application that involves displaying records in a dxdatagrid. The challenge we are facing includes: Different schema each time, with data coming from various tables. The need to add/edit records. Displayi ...