Reputation: 1
I would like to set a debounce time on a button from my HTML in Angular. This is the code I already have.
const button = document.getElementById('mybtn') ;
const click$ = fromEvent(button, 'click');
const debounceClick$ = click$.pipe(debounceTime(500));
debounceClick$.subscribe(() => {
console.log('debounceClick$');
});
Somehow I can't run the program as I get this compile error:
Error: src/app/app.component.ts:23:32 - error TS2345: Argument of type 'HTMLElement | null' is not assignable to parameter of type 'FromEventTarget<Event>'.
Type 'null' is not assignable to type 'FromEventTarget<Event>'.
I'm would like to have a compile ready code which also gives me the desired result. Desired result: button only clickable every 500ms
Upvotes: 0
Views: 993
Reputation: 7179
document.getElementById()
is not guaranteed to return an element since the provided identifier might not exist on the page. Because of this, TypeScript types the return value as HTMLElement | null
.
You need to let the TS compiler know that button
will not be null
since fromEvent
doesn't accept null
as a first argument.
You could use an if
statement:
const button = document.getElementById('mybtn');
if (button != null) {
// button's type should now be just HTMLElement
const click$ = fromEvent(button, 'click');
// ...
}
Or you could could assert that you know button
will exist using the non-null assertion operator (!
):
const button = document.getElementById('mybtn');
const click$ = fromEvent(button!, 'click');
// ...
Of these approaches, the if
statement is more robust. You don't know if the user or another script will have removed button
from the DOM, so you shouldn't assert you know it's non-null.
One other thing, unless you're using click$
somewhere, you don't need it as a standalone variable. You can achieve the same result like this:
const button = document.getElementById('mybtn');
const debounceClick$ = fromEvent(button, 'click')
.pipe(debounceTime(500));
debounceClick$.subscribe(() => {
console.log('debounceClick$');
});
Upvotes: 4