angularparent-child

Sending data from a parent component to a specific child component


I have a child component that I am showing multiple samples of them in a parent component as: parent.html:

<app-parent>
   @for (item of Items; track item; let index = $index) {
       <app-child [id]="index" [weatherStatus]="weather">
       </app-child>
   }
</app-parent>

parent.ts

Items : child [] = [];
...

//for first child
this.weather = "sunny"

//for second child
this.weather = "cloudy"

//for third child
this.weather = "rainy"

child.ts:

@Input() weatherStatus = '';

ngOnChanges(changes: SimpleChanges) {
 if (changes['weatherStatus'])
     console.log('Input data changed:', this.weatherStatus);
}

child.html

<p>
  Today weather is: {{weatherStatus}}
</p>

I am using @Input() decorator to pass some data from parent to child. Currently when I send a data from parent, all of the child components get the same value. But I want to send a specific value for each child. For example, if I have three children, the value "sunny" be sent to the first child, "cloudy" to the second and "rainy" to the third one. What is the best approach to do it?


Solution

  • I see you are using weather variable from component.ts file which is a global variable, and it's not defined separately for each item.

    I have prepared a stackblitz demo - Click here to answer your query. Please check and let me know if you need anything else!