Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

child component doesn't update when I update input variable - Angular

I have child component and in this I pass as input an value from parent component. In parent component I'm updating this input variable on event emmiter trigger, but the child component doesn't update. I've checked in augury the input variable updates. Why child component don't updates?

ParentComponent.html

<app-child
[data]="data"
(filterEmmiter)="filter($event)">
</app-child>

ParentComponent.ts

data: any;
.
.
.
getUsers() {
  this.usersService.getAllUsers().subscribe(res => {
    this.data = res;
  });
}
.
.
.

filter(data){
  this.data = data
}

like image 445
erzen Avatar asked Mar 31 '26 19:03

erzen


2 Answers

you can try like this, here you want to get the data from the parent component to child component, Here your parent component is ParentComponent and child component is app-child so here for getting the data from parent to child we can use ngOnChanges(changes: SimpleChanges)

ParentComponent.html

<app-child
[data]="data"
(filterEmmiter)="filter($event)">
</app-child>

child.component.ts


import {Component, OnChanges, SimpleChanges, Input} from '@angular/core';

class Child  implements OnInit, OnChanges {

    @Input() Data: any; // here is the data variable which we are getting from the parent 

    constructor() {}

    ngOnChanges(changes: SimpleChanges) {
      console.log(changes); // here you will get the data from parent once the input param is change
    }   

}

like image 149
Yash Rami Avatar answered Apr 03 '26 08:04

Yash Rami


Recently I was also facing something similar, in my case, using the Onchanges method in the child, I saw that the input change happens after the logic that I want to execute then the a new value of the input doesn't get reflected in this logic.

What I did was to force the detect changes in the place I assigned the input data like this:

I add this to my constructor

 constructor( private changeDetector: ChangeDetectorRef) {} 

Then where I assigned a value to the data

this.data=something
this.changeDetector.detectChanges();

After that, I notice that the method onChanges was called first and then the logic with the new value of the input, After that I just set manually the value of the input in the Onchanges method that should be placed in the child component

 ngOnChanges(changes: SimpleChanges): void {
    this.put= changes.input.currentValue;
  }
like image 23
Okyam Avatar answered Apr 03 '26 08:04

Okyam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!