Angular cannot detect input value changes using @Input()

I use set-get in order to detect changes in Angular and pass value from parent to child as shown below:

parent:

<child [employeeId]="empId"></child>

child:

private _employeeIdId: number;

@Input() set employeeIdId(value: number) {
    this._employeeIdId = value;

    // set dropdown value
}

get employeeIdId(){
    return this._employeeIdId;
}

After updating record, I want to pass empId from parent to child to refresh the table list (refetch again with the same Id). But as this value is already the same, set employeeIdId does not fired. Any idea how to fix it?

3 thoughts on “Angular cannot detect input value changes using @Input()”

  1. It is known that ngOnChanges hook won’t be triggered if the @Input property’s underlying reference hasn’t changed. While someone else could provide a more elegant solution, here is an inelegant workaround by making the @Input property an object and forcing reassignment using JSON.parse(JSON.stringify()).

    Parent

    export class AppComponent {
      employeeId: { id: number } = { id: 0 };
    
      setEmployeeId(value: number) {
        this.employeeId = { id: value };
      }
    
      forceLoad() {
        this.employeeId = JSON.parse(JSON.stringify(this.employeeId));
      }
    }
    

    Child

    export class ChildComponent {
      private _employeeIdId: number;
    
      @Input() set employeeIdId(value: { id: number }) {
        console.log("Set id in child:", value.id);
        this._employeeIdId = value.id;
      }
    }
    

    Working example: Stackblitz

    Note: Since the type definition is changed, the getter to return the .id property wouldn’t work. You could use something like getId() for it instead.

    Reply

Leave a Comment