1

I have an issue defined by the following steps:

  1. I pass a value from a parent to a child via @input
  2. My child binds this @input to an input element
  3. I pass back the changed value to the parent via an event emitter
  4. My parent captures this event and passes to a function.
  5. Function realizes the input is invalid and changes the value back to a valid value
  6. This changed value is passed back through the @input to the child
  7. I repeat these steps
  8. However my function is now changing the value back to the exact value it was on its prior @input so the child component does not pick up the change and my parent and child are now out of sync and stay that way until I enter in a valid value again.

I have created a stackblitz here to illustrate this issue. https://stackblitz.com/edit/angular-kbpx7r If you enter 99 and then 99 again you will see the parent and the child get out of sync. You can enter any number under 10 to bring them back into sync but My issue is I need to figure out how to keep them in sync at all time.

user10012
  • 647
  • 1
  • 8
  • 23
  • Possible duplicate of [Angular 2+: Update @Input property when parent value changes](https://stackoverflow.com/questions/49249548/angular-2-update-input-property-when-parent-value-changes) – WasiF May 23 '19 at 04:20

2 Answers2

0

So, your problem is the following:

When you called 99 the second time, parentValue is always set at 5.

So for the child, there is no change. Nothing get through ngOnChanges at this moment.

And this is why the child doesn't get the 5 the second time.

To confirm my though, you can test :

if(newValue.value > 10){ 
  this.parentValue = 4;
  this.parentValue = 5;
}else{
  this.parentValue = newValue.value;
}

Then you will have two calls and so a change.

Wandrille
  • 6,267
  • 3
  • 20
  • 43
  • Unfortunately I think it has something to do with the change cycle so even though we set it to 4 because it's being set back to 5 before this change cycle it doesn't get passed. I think the solution is to manually flag that the value has changed, but I am not sure how to do that. – user10012 Mar 14 '19 at 22:45
0

I added (change) event to the input field in child component and I see it works as expected. I see the change was not detected earlier. (change) event tracks it now. Kindly try and share feedback/suggestions.

child.component.html

<p>
  Keep Number under 10<br>
<input id="{{id}}" [(ngModel)]="value" (blur)="emitValue($event)" (change)="emitValue($event)" type="text"><br>
The child value is: {{value}}
</p>
javapedia.net
  • 2,531
  • 4
  • 25
  • 50
  • Ok, I'm impressed. But can you help me understand why this works yet still doesn't change the parent value unlit blur? – user10012 Mar 14 '19 at 23:55