1
votes

When I make a change to a property of an object, Angular's default change detection is not working:

@Component({
    selector: 'parent-comp',
    template: `<child-comp [mutableObject]="mutableObject"></child-comp>`
})
export class ParentComp implements OnInit {

    mutableObject: MutableObject = { someProp: 'hello' };

    onClickedSomething() {
        this.mutableObject.someProp = 'goodbye';
    }
}

@Component({
    selector: 'child-comp',
    template: `<h1>{{ mutableObject.someProp }}</h1>`
})
export class ChildComp implements OnInit, OnChanges {

    @Input() mutableObject: MutableObject;

    ngOnInit() {}

    ngOnChanges(changes: SimpleChanges) {
        console.log('change detected');
    }
}

ngOnInit gets called in child component the first time both parent and child components load, but when onClickedSomething() method changes the property value, the child component doesn't detect the change. I made sure that ChangeDetectionStrategy.OnPush is not being used. What could be going wrong here?

1

1 Answers

3
votes

Nothing is going wrong here. Like you say, the underlying reference to the object isn't changed. So Angular doesn't honour the change in object properties. Try to force it using the spread operator and reassign the variable.

export class ParentComp implements OnInit {
  mutableObject: MutableObject = { someProp: 'hello' };

  onClickedSomething() {
    this.mutableObject = { ...this.mutableObject, someProp: 'goodbye' };
  }
}

Obviously the spread operator in the assignment is redundant here since the object contains only one property. But it'll be required when there are multiple properties and you wish to change only few of them.