Reputation: 223
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.
Upvotes: 3
Views: 9286
Reputation: 4274
As I mentionned in the comment, valueChanges will react to copy/pasted values or values that are inserted automatically from the browser (autofill forms). Also, key events might not be the right choice on mobile device where other events might lead to values being changed in the form.
In my opinion, KeyListeners should only be used if there is no good alternative. They might event affet the performance of your app.
Upvotes: 1
Reputation: 6283
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
Upvotes: 4
Reputation: 828
I agree with Tim's comment to your post: "keyUp" is not fired when you e.g. copy-paste some text into your form, while valueChanges AFAIK should also be fired in this case
Upvotes: 1
Reputation: 1514
If u use valueChanges u can use pipe operator as well and manipulate input value. For example:
this.formControl.valueChanges
.pipe(
distinctUntilChanged(),
filter(v => v.length > 3),
tap(console.log))
.subscribe();
Upvotes: 2