Search code examples
angularrxjsangular-forms

FormControl valueChanges.subscribe vs keyup


Simple question which didnt came into my mind before.

I started on a project and found code:

<input (keyup)="someFunc($event)" [formControl]="someControl">

Because I am refactoring all forms, my first thought was to remove (keyup) and use someControl.valueChanges.subscribe(..), but now I have doubts because if I do so, I just add more code to the component (f.ex. import Subscription, OnDestroy also to unsubscribe, then someControl.valueChanges.subscribe). So compared to keyup, valueChanges.subscribe adds much more code.

Are there any benefits in it that I do not realise?

p.s. I know, that with using keyup, it fires when user releases button, while valueChanges.subscribe when user presses button. But in my case, such difference doesnt matter.


Solution

  • I would use valuesChanges() over keyup as you are less likely to miss anything as it is listening to a change to the form control value rather than an event. So however it is changed wither pragmatically or via dom the changes will be noticed.

    This will need to be handled with unsub though as it is not a http request the subscription will not manually unsub when you are done. I would try something like.

    public subscriptions = new Subscription();
    
    this.subscriptions.add(this.formControl.valueChanges
    .pipe(distinctUntilChanged()) // makes sure the value has actually changed.
    .subscribe(data => console.log(data)));
    
    public ngOnDestroy(): void
    {
        this.subscriptions.unsubscribe();
        // ensure when component is destroyed the subscription is also and not left open.
    }
    

    example of unsubscribing can be found here