Transferring information through parent-child components via onChange

I have a question regarding data binding. In my project, I have a parent component and two child components: Parent:

    directives: [firstChild,secondChild],
    template:'
 <first-child [showList]="showList" (emitShowList)="getShowList($event)"></history-months-avg-header>
 <second-child [showList]="showList" (emitShowList)="getShowList($event)"></history-months-avg-header>
    '
    export class FlexProductListComponent {
      private showList:any[]=[];

      getShowList(show:any[]){
            this.showList = show;
            console.log('new list',this.showList);
        }

    }

First child component:

directives: [],
        template:'
<button  (click)="showHistoryDetails();" ><i class="fa fa-angle-double-right" aria-hidden="true"  ></i></button>

export class firstChild{
    @Output() emitShowList = new EventEmitter<any[]>();
    @Input() showList: any[];
    public showHistoryStatus: boolean = false;

     showHistoryDetails() {

            if (this.showHistoryStatus) {
                this.showHistoryStatus = false;
                this.showList =             this.removeFromShowList(this.showList,this.HistoryComponent);
                console.log('changing to no',this.showList);
                this.emitShowList.emit(this.showList);
            } else {               
                this.showHistoryStatus = true;
                this.showList.push(this.HistoryComponent);
                this.emitShowList.emit(this.showList);

            }
        }

    '

Second child component:

/*component etc*/

directives:[],
template: ``
export class secondChild{
@Input()   allHistoryChannels:any;
@Input() set showList(var:any[]){
console.log(var);
/*other actions*/
};

Now, the issue arises. When I click on the button in the first child component to add or remove an item from the array and then emit the edited array (showList) to the parent component. The parent component receives the updated data and overrides the current data in the showList property. The new value in the showList property should be passed down to all bound child components. However, it doesn't work as expected. The second child component only logs at the start when the show list is empty. I always assumed that when we override a parent property that is bound to child components, the new value would propagate to all bound child components. It seems like I am mistaken. Can someone help me find a solution to this problem? Thank you :)

Answer №1

If you're looking to handle input changes in Angular, consider exploring the OnChanges interface: https://angular.io/docs/ts/latest/api/core/index/OnChanges-class.html

In order to utilize this interface, you will need to implement it within the Child component and define actions to take when the input changes.

Here's an example code snippet from the provided link:

@Component({selector: 'first-child', template: `...`})
class MyComponent implements OnChanges {
  @Input()
  prop: number;
  
  ngOnChanges(changes: SimpleChanges) {
    // Accessing specific input change like 'showList'
    changes['showList'] . . .
    
    // Implement your desired functionality for 'showList' here
  }
}

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

What is the reason for my Firestore listener consistently retrieving data from the server despite having offline persistence enabled?

Incorporating Firebase JavaScript Modular Web Version 9 SDK into my Vue 3 / TypeScript application. My understanding is that when utilizing real-time listeners with offline persistence in Firestore, the process should proceed as follows: Upon initializat ...

Difficulty encountered while trying to run the ngx-admin dashboard designed for Angular

I encountered some issues during the installation of node modules. Can someone please assist me with this? Angular CLI: 13.3.0 Node: 16.14.2 Click here to view the list of problems Any help would be greatly appreciated. ...

Closing the side navigation bar when a router link is clicked on small devices

In my project, I have implemented the side-nav component for routing between different components. Here is how it looks: https://i.stack.imgur.com/v6hE8.png However, I am currently facing an issue with the side-nav. On mobile devices, the side-nav appear ...

Guide on organizing a multi-dimensional array of objects based on property value using javascript?

I am faced with the challenge of sorting a multidimensional array based on values, but the selection is dependent on the parentID. This is my current array: const result = [ [{value: 123, parentID: 1}, {value: 'string123', parentID: 2}], [{ ...

The text "Hello ${name}" does not get substituted with the name parameter right away in the message string

I'm struggling to get the basic TypeScript feature to work properly. Everywhere I look on the Internet, it says that: var a = "Bob" var message = 'Hello ${a}' should result in a console.log(message) printing "Hello Bob". Howeve ...

Prisma: Incorrectly identifying existing items where the list contains any of the specified items

Within my Prisma model, I have a property designated to store a list of phone numbers in the format phones String[] @unique When making an API call with a model that may include one or more phone numbers, my goal is to locate any existing record where any ...

Encountered an unexpected import token in Angular2 (SystemJS)

i am trying to find a solution for this issue in my Angular2 project. I encountered an error and need assistance: `"(SystemJS) Unexpected token import SyntaxError: Unexpected token import at Object.eval (http://....../app.module.js:14:25) at eval (h ...

What is the best way to eliminate a specific set of characters from a string using TypeScript?

Imagine you have the following lines of code stored in a string variable: let images='<img alt="image1" height="200" src="image1.jpg" width="800"> <img alt="image2" src="image2.jpg" height="501" width="1233"> <img alt="im ...

Despite the presence of a producer and topic, sending Kafka messages is proving to be a challenge

Currently, I am using TypeScript and the KafkaJS library on my local machine with a single Kafka broker. After successfully connecting a producer, confirming the creation of my topic, and creating messages like so: const changeMessage = { key: id, ...

Developing a TypeScript PureMVC project from scratch

Currently, I am working on a project to implement PureMVC in TypeScript using npm and grunt. Unfortunately, PureMVC has ended development on their project and there is a lack of resources for PureMVC in TypeScript online. The documentation only provides in ...

I encountered difficulties connecting mongoose to my local MongoDB server

Hello Everyone! Currently, I am in the process of linking my node.js project to mongodb. Initially, everything worked smoothly when I used mongodb atlas. However, when I attempted to connect it using mongodb compass, I faced some issues and nothing seemed ...

Scanning for devices on Ionic 2/3 made simple: How to easily exclude unwanted application and Android directories

I'm currently working on a gallery application that enables users to choose images from their phone and transfer them to a kiosk. Upon loading the application, it searches the entire device for folders containing images and organizes them into an albu ...

Troubleshooting SPFX and Angular: Difficulty accessing service in component.ts file

I recently developed a project using the SharePoint SPFX framework and integrated all the necessary Angular (6.0 or 7.0) TypeScript packages. While Angular seems to be functioning properly within my SPFx webpart, I encountered an issue when attempting to c ...

When working with the "agora-rtc-sdk-ng" package, an error may be thrown by Next.js stating that "window is not defined"

Currently, I am in the process of incorporating the "agora-rtc-sdk-ng" package for live streaming with next.js and typescript. import AgoraRTC from 'agora-rtc-sdk-ng'; However, when I try to import it, an error is thrown as shown below: https:/ ...

What are the steps for importing a file into a React app that is built using Create React App as plain text?

Objectives I aim to showcase code snippets from the project itself for reference. I intend to keep the displayed code up-to-date with its implementation. I prefer not to remove myself from create-react-app This React project, built using create-react-ap ...

(NextAuth) Error: The property 'session' is not found within the existing type '{}'

While working on a NextJs project with NextAuth, I encountered the following error: "Type error: Property 'session' does not exist on type '{}'.". To resolve this issue, I added the session property to my _app.tsx file as sugg ...

I am encountering an Ionic issue where the Footer selector fails to work properly

I am working on my Ionic page and I have created a separate component for the footer. However, when I use the footer selector in my page, an error is displayed. This is the code for my "foot-card" component (foot-card.ts): import { Component } from &apos ...

The Angular frontend is making me wait for the transfer of 20mb during the initial load

My Full Stack Website is built using the MEAN stack. The front end was developed in Angular5 and deployed on the server. However, I am encountering an issue where it takes a significant amount of time to load for the first time as it needs to download appr ...

How can you add or remove an item from an array of objects in Angular/RXJS using Observables?

Purpose: The goal is to append a new object to an existing Observable array of objects and ensure that this change is visible on the DOM as the final step. NewObject.ts: export class NewObject { name: string; title: string; } Here's the example ...

Multiple consecutive XHR requests failed without any error message. The cause remains unknown

Here is the content of my package.json file: canActivate in my code:</p> imports: [ BrowserModule, FormsModule, ReactiveFormsModule, RouterModule.forRoot([ {//route configs path: '', redirectTo: '/cfbsetup', pathMatch: &a ...