Angular update component

In a scenario where data is being sent from two different components - let's call them OneComponent and

TwoComponent. These components send their data to a <code>ResultComponent
through the Input() decorator. Within the ResultComponent, the received data is merged using the OnChanges interface:

  ngOnChanges(changes: SimpleChanges) {
    if (changes['dataFromCompTwo']) {
      this.dataFromComp = this.dataFromCompTwo;
    }
  }

The issue arises when the component is instantiated twice, causing the data to double up. How can we ensure that only the latest sent data is displayed, regardless of which component it came from?

STACKBLITZ => I want to display the result "Here is the result" just once.

Answer №1

When it comes to inter-components communication, it is essential to adopt one of the various techniques outlined in this Angular documentation page.

In my opinion, I lean towards utilizing a service for communication as it ensures that components are not tightly linked: their communication method remains independent of their placement in the DOM, allowing flexibility in moving them around without causing any disruptions.

Answer №2

When you have two components sending changes, you can access them like this:

  • changes.componentOne
  • changes.componentTwo

In addition to this, SimpleChanges also includes a property called firstChange, which allows you to determine if it is the first change coming from that specific component. You can check this using the following syntax:

  • changes.componentOne.firstchange - This indicates that it is the initial change sent by the component.

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

Angular, dividing a row between two components

Can components share the same row? Currently, the side navbar takes up 2 columns, but I want each card to take up exactly 3 columns. This is the current layout: https://i.sstatic.net/J0CRF.png Here is the expected layout: https://i.sstatic.net/GupPd.png ...

Effortlessly apply mapping, filtering, reducing, and more in JavaScript

Array#map and Array#filter both create a new array, effectively iterating over the original array each time. In languages like rust, python, java, c#, etc., such expression chains only iterate once, making them more efficient in certain cases. While this ...

Oops! Before proceeding, make sure to call TestBed.initTestEnvironment() first

Currently, I am experimenting with testing a service in Angular. Below is the code snippet I am working on: describe('AddressService', () => { let service: AddressService; let injector: TestBed; let httpTestingController: HttpTesting ...

Patience is key when awaiting the completion of several promises

I am currently utilizing the SQLStorage feature provided by the Ionic platform. The remove function within this tool returns a promise. Within my code, I have a need to remove multiple values and then execute some additional code once all removals are comp ...

Create a grid layout with Angular Material by utilizing the *ngFor directive

I've encountered a situation where I need to manually insert each column in my component data. However, I would prefer to dynamically generate them similar to the example provided at the bottom of the page. <div> <table mat-table [dataSour ...

Ionic3 footer using ion-tabs

Is there a way to create a common footer for all pages with 5 buttons, where the first button is selected by default? The page opened by this first button should have three tabs. I have already created the tabs but am unsure how to add the footer without r ...

The issue of the list view button not responding to click events in Angular2 NativeScript

I have been working on implementing an onclick event for a listview item button. Below is the code snippet that I have tried, but unfortunately the console log is not being triggered when the button is clicked. I am unsure of what the problem might be in ...

What steps should I take to make create-react-app compile code that is located outside of the /src directory

I am facing a dilemma with my project structure, as it consists of two projects: /frontend and /backend. The frontend project uses create-react-app-typescript. The challenge is sharing code between these projects, particularly the type definitions for API ...

What is the best way to access the data stored within a Promise object in a React application?

Below is the snippet of my code that handles parsing application data: async function parseApplication(data: Application) { const fieldGroupValues = {}; for (const group of Object.keys(data.mappedFieldGroupValues)) { const groupValue = data.mappedF ...

Obtaining selected table data in Angular 4 when printing from a component

I'm currently facing an issue with passing data from a table component to a print component through a service. I am unable to access the shared data in the print component. Here is the data that needs to be passed: [{barCode: "31568308949" checked: t ...

Can you provide any tips on how to effectively incorporate slide-down and slide-up animations in Angular 4.*?

Hello, I'm new to working with Angular 4 and I'd like to create a slide down and up animation in Angular 4. Could someone please provide me with the necessary code? @Component({ ... animations: [] ... }) Thank you for your help! ...

Engaging Angular Universal for internal API calls through Express

After researching numerous tutorials and guides on integrating SSR (server-side rendering) into existing angular CLI & Express projects, I successfully configured node with SSR. However, I encountered difficulties in making API calls. My goal is to have a ...

Enforcing rigorous type validation for property type using the property decorator

Is it possible to create a property decorator in Typescript that validates the type of the decorated property? Specifically, I want to restrict the decorator to only work on boolean class properties and not on other types like string. Can this be achieved ...

What is the most effective way to access a variable from a service in all HTML files of Angular 2/4 components?

In my angular 4 project, I have an alert service where all components can set alerts, but only specific components display them in unique locations. My question is: how can I access a variable from this service across all HTML files? The structure of my s ...

Using FormArray in Angular 5 to dynamically populate data

Using formarray in Angular 5, I have successfully implemented the functionality to add and remove rows. However, I now face a new challenge - how can I populate the form with existing data for multiple rows? For instance, if I have data for 3 rows, I want ...

Differentiating Layout Routing in Angular 2

In my unique Angular 2 application, I am facing a challenge with the layout. The home page has a completely different layout compared to the rest of the app, which only share a navigation bar. Here are some sample URLs: http://localhost:4200/ <= ...

React app version displaying incorrect links to CSS and JS files

I have been immersed in a React project called Simple-portfolio, you can find the GitHub repository here: https://github.com/Devang47/simple-portfolio and the live site at this URL: While everything works smoothly on the development server, I encountered ...

Calculate the total sum of an array in Angular based on a specific condition of another key

How do I calculate the sum of array elements where sel1, sel2, or sel3 is equal to 1 from the following Array? [ { "sel1": 0, "sel2": 1, "sel3": 0, "price": 10 }, { "sel1": 0, "sel2": 1, &qu ...

A different component experiences an issue where Angular Promise is returning undefined

This is the carComponent.ts file containing the following method: async Download() { try { const settings = { kit: true, tyres: true, serviced: false, }; const [kits, tyres] = await Promise.all([ this.c ...

A guide on obtaining the component reference linked to ElementRef within Angular 2

I am currently working with a component in my template: <vector-editor #scaleControl [x]="scaleX" [y]="scaleY" [z]="scaleZ" > </vector-editor> The structure of the vector-editor ...