Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`@HostListener` of `e: TouchEvent` causes Firefox to crash with "ReferenceError: TouchEvent is not defined."

Using @HostListener with the event parameter explicitly typed as a TouchEvent, causes Firefox to crash with the following error message:

ReferenceError: TouchEvent is not defined.

An example:

@HostListener('touchstart', ['$event']) // or 'touchend', 'touchmove'
onTouchStart(e: TouchEvent): void {}

I could come up with a few ways to prevent this myself:

  • use e: TouchEvent | any or e: any (or don't specify a type at all)
  • use elRef.nativeElement.addEventListener('touchstart', (e: TouchEvent) => {})
  • use Observable.fromEvent(elRef.nativeElement, 'touchstart').subscribe((e: TouchEvent) => {})

But using any or | any seems like a hack, and the other two options don't take advantage of the framework. Is there another, better and safer way to deal with this issue, and if not, which option is preferable?

(Maybe someone can also explain what Angular is actually doing and why this error only happens when the event is explicitly typed as a TouchEvent...)


EDIT: The issue is still present in Angular 7. EDIT: This issue has apparently been fixed in Angular 6.

like image 202
pfeileon Avatar asked Jul 01 '18 14:07

pfeileon


1 Answers

When there is decorator on a method, typescript compiler stores types of parameters in the metadata, which fails in desktop Firefox because TouchEvent is not defined there. It can be solved by polyfilling the missing types with stubs. Just add the following code to polyfills.ts

for (const type of ['TouchEvent']) {
    if (typeof window[type] === 'undefined') {
        window[type] = function () { };
    }
}

To polyfill other types, add them to the list. A word of warning - this may break code that checks for existence of touch events by detecting window.TouchEvent.

Anyway, the problem only seems to happen with the JIT compiler, so it will probably disappear with Ivy.

like image 128
IztokK Avatar answered Oct 17 '22 13:10

IztokK