简体   繁体   中英

Include JS class in an Angular project

I need to include the JavaScript code below to my Angular app (got this one from our designer team).

Before:

const body = document.querySelector('body');
window.addEventListener('touchstart', () => {
});
window.addEventListener('touchmove', (e) => {
  body.classList.add('-scroll');
});
window.addEventListener('touchend', (e) => {
  body.classList.remove('-scroll');
});

What I've tried - is to add a Scroll class for it, like in the code below. As a result - I have no errors, but also no result; probably the code is wrong. Can you please tell me how to fix it, or maybe offer a better solution for this.

After (not working):

public ngOnInit(): void {
  setTimeout(() => {
    new Scroll().init();
  }, 100);
}

export class Scroll {
  body: any;

  init() {
    this.body = document.querySelector('body');

    window.addEventListener('touchstart', () => {});
    window.addEventListener('touchmove', e => {
      this.body.classList.add('-scroll');
    });
    window.addEventListener('touchend', e => {
  this.body.classList.remove('-scroll');
    });
  }
}

Thank you in advance!

Use angular HostListener decorator see usage

export class Scroll {

  @HostListener('window:touchstart', ['$event'])
  onWindowTouchstart($event) {
    // your code
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM