DEV Community

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

Collapse
 
gc_psk profile image
Giancarlo Buomprisco

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 😅

Collapse
 
bo profile image
Bo Vandersteene • Edited

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

Thread Thread
 
abelardoit profile image
abelardoit

And what's the solution to avoid this situation, please? Would you opt by adding a setter to the property?

Thread Thread
 
bo profile image
Bo Vandersteene

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:

 ngOnChanges({ name, email }: SimpleChanges) {
    const username = name?.currentValue ?? this.name ?? email?currentValue ?? this.email
    this.username$.next(username);
  }
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
abelardoit profile image
abelardoit

Thanks for replying asap! Best regards.