Discussion on: Angular: Setters vs ngOnChanges - which one is better?

reibo_bo profile image
Bo Vandersteene
  ngOnChanges({ name, email }: SimpleChanges) {
    const username = name.currentValue || email.currentValue;

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.

gc_psk profile image
Giancarlo Buomprisco Author

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 😅

reibo_bo profile image
Bo Vandersteene

Ok so if you have a component that uses your code like this

<my-component [email]="email$ | async" 
                               [username]="username$ | async"> </my-component>

If the input of the observables look like this

email$    = -E----
username$  =  ----U--

Then the ngOnChanges will be called first with only email and then with only username so one of the two is undefined. Only the values that are changed are submitted in the SimpleChanges