angularcomponentsangular-changedetection

Angular 9: how to re-render component


I have one parent and one child component. If the child component updates its value internally I am unable to update value back from Parent.

See the example in this Stackblitz: https://stackblitz.com/edit/angular-ivy-tynepp. When the child component loses focus I fire an event and the parent resets value of the child component. But I think that because the parent's "this.value" didn't change that the update doesn't trigger detection changes in the child.

How can I solve this dilemma?


Solution

  • As you said, change detection is not triggered because the bound value has not changed. You can force an update of the data binding with the following steps:

    1. Set a temporary value
    2. Call ChangeDetectorRef.detectChanges()
    3. Reset the value
    constructor(private changeDetectorRef: ChangeDetectorRef) {}
    
    resetValue() {
      this.value = "____TempValue____";
      this.changeDetectorRef.detectChanges();
      this.value = "";
    }
    

    See this stackblitz for a demo.