Angular replace component

391 views Asked by At

There is a case where the data are being sent from two different components; let's say OneComponent and TwoComponent and there is a ResultComponent which receive these data via Input() decorator. Also, in ResultComponent the data are merged using OnChanges interface:

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

and data are shown in this component, but component is instantiated twice and the data are double. How to check if data are already sent from one of the components and show only last sent data?

STACKBLITZ => I would like to show Here is result just once.

2

There are 2 answers

0
Qortex On BEST ANSWER

This is inter-components communication. You should use one of the techniques described on this Angular documentation page.

I personnaly favor communication through a service because components are then not coupled at all: the communication method does not depend on their inclusion in the DOM so you can move them around as you please, it won't break.

0
Mac_W On

if you have two components sending changes then you can access these using:

  • changes.componentOne
  • changes.componentTwo

The SimpleChanges has another property called firstChange which you can use to check if this is the first change coming from that specific component like this:

  • changes.componentOne.firstchange - this would mean that this is the first change sent by the components