0
votes

I'm having a problem with Angular 4, I have a list of components and each of those components have a mat-menu (Angular material component) inside. I'm receiving a lot of warning in the Chrome console:

"[Violation] Added non-passive event listener to a scroll-blocking 'touchstart' event. Consider marking event handler as 'passive' to make the page more responsive."

I have removed that component and as I can see the amount of warning has decreased. Any of you know what's happening there? is something inside the mat-menu who is triggering that warning ?

1

1 Answers

0
votes

You are using Angular 4. This is a very old version. The violation warning in chrome is relatively new, considering how old angular 4 is. Which means that newer versions of angular, and the material library, have updated to prevent this warning.

The only way for you to get rid of this warning is to downgrade chrome or finally update your angular (and material) version


If you cannot update, you can create an event manager plugin. With this you can capture events when they are binded to elements. It could be however that the events in material are not binded this way, and are immediately binded using either fromEvent from rxjs or the standard element.addEventListener, but you can try:

In your AppModule you add this provider:

import { EVENT_MANAGER_PLUGINS } from '@angular/platform-browser';

@NgModule({
  providers: [
    {
      provide: EVENT_MANAGER_PLUGINS,
      useClass: PassiveEventsOptionPlugin,
      multi: true
    }
  ]
})
export class AppModule {}

And your event plugin can look like this. Again, this is untested:

@Injectable()
export class PassiveEventsOptionPlugin {
  private readonly passiveEvents = [
    'touchstart'
  ];

  constructor(@Inject(DOCUMENT) private doc: any) {}

  supports(eventName: string): boolean {
    return this.passiveEvents.some((event) => eventName.startsWith(event));
  }

  addEventListener(el: HTMLElement, event: string, listener: EventListener): () => void {
    // this is the important part. Adding the passive option
    const options = { passive: true };
    element.addEventListener(type, listener, options);

    return () => element.removeEventListener(type, listener, options);
  }

  addGlobalEventListener(
    element: GlobalEventTarget,
    eventName: string,
    listener: EventListener
  ): () => void {
    let target: EventTarget | undefined;

    if (element === 'window') {
      target = window;
    } else if (element === 'document') {
      target = this.doc;
    } else if (element === 'body' && this.doc) {
      target = this.doc.body;
    }

    return this.addEventListener(target as HTMLElement, eventName, listener);
  }
}