3
votes

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?

3
Please check Stackblitz link I provided - Andrei V
From the link above, emphasis in the original: "Make sure all information necessary to reproduce the problem is included in the question itself" - jonrsharpe
Do you want only to change the value of the child component from the parent component? Or have the same value on both components? - bjdose
Just value of the child component @bjdose - Andrei V

3 Answers

3
votes

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.

0
votes

Another simpler approach to get this can be to use the template variables as you can see in the example below:

parent.component.html

<app-my-child 
  #child
  (lostFocus)="child.value = ''"></app-my-child>

Solution available here.

0
votes

I have created a Directive for my project and it's really easy to use

<ng-container *rerender='changingInput'>
  this content will be re-rendered everytime `changingInput` changes
</ng-container>

Check out my Gist for more details.