0

In Angular6, i am getting a variable value to client from Parent using @Input()

@Input() orderdata: OrderData;

and binded to a field using [ngModel] and (ngModelChange) function.

In the child component when user changes this variable value (binded) I need to do a validation comparing the new value and old value. How to do this?

I tried assigning orderdata to a new variable

oldorderdata = orderdata; 

and then later perform the comparison. But when ever user changes the orderdata at the moment itself oldorderdata is also changed.

1

2 Answers 2

2

Generally when you assign objects to each other in JS, you're not assigning their values, you're just assigning to their memory references.

That's why when the orderdata is changed, the oldorderdata will also change since it was pointing to the same object in memory.

To prevent this, you can use the spread operator(...) in ES6 like this:

oldorderdata = {...orderdata};

This will spread all the properties from orderdata into the oldorderdata object.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Siddharth. Above solution plus declaring the oldorderdata as private (as advised in discussion stackoverflow.com/questions/45058145/…) resolved the problem
Glad I helped!!
0

the variable will generally change since you are binding it with [(ngModel)], to make the comparison you need to bind the variable to output of the comparison function instead

1 Comment

I ngModel binding on orderdata variable and there is no binding on oldorderdata. How change in orderdata is changing the oldorderdata?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.