This post was originally published on Angular Bites
Getting notified about an Angular component's property changes is normally done in 2 ways:
...
For further actions, you may consider blocking this person and/or reporting abuse
If you take this code in consideration, you need to pay attention, that both values are changed on the same time. If the ngOnChanges is called 2 times for each value, than this one can give some unwanted sideEffects.
Hi! do you mean that name or email could be undefined? TBH I'd never ship this to production - just needed a short example with multiple inputs 😅
Ok so if you have a component that uses your code like this
If the input of the observables look like this
Then the ngOnChanges will be called first with only
email
and then with onlyusername
so one of the two is undefined. Only the values that are changed are submitted in theSimpleChanges
And what's the solution to avoid this situation, please? Would you opt by adding a setter to the property?
It depends what do you want to achieve with this function.
Like I read this it should only take the email into account if the name is empty so something like this:
Thanks for replying asap! Best regards.
I tend to avoid setters with the inputs if the inputs have dependency on other inputs because then the order inputs to the components matter.
see this link for further details: medium.com/generic-ui/a-deep-dive-...
Surprisingly we had this discussion as well recently. We came up with using setters as a preferred option. I don’t see any major disadvantages of that approach. 👍
Try this approach. Works fine for me.
Hi!
i prefer the first approach too (setter). I think that the code is definitely more clean than using the hook. Thanks for sharing your tip!
Hi there,
Why did you affirm that (to receive all the inputs at once) is (sometimes) a sign of a code-smell?
What's wrong by passing several inputs at once?
Thanks! Brs.
I'm curious too! :)
Great and short summary :)
Have you considered performance differences with default change detection strategy?
I haven't - but even then I'd be surprised if there were any noticeable differences :)