Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular Directive: Use parent class variable in callback function

I created a directive which takes a callback function as an input. This callback is called when an event touchstart on the parent gets fired:

@Directive({
  selector: '[appSwipeRight]',
})
export class SwipeRightDirective implements AfterViewInit{
  @Input() appSwipeRight!: () => void;

  constructor(private elementRef: ElementRef) {}

  ngAfterViewInit(): void {
    fromEvent(this.elementRef.nativeElement, 'touchstart').subscribe(() => {
      // ...
      this.appSwipeRight();
    });
  }
}

@Component({
  selector: 'app-general',
  template: '<main class="main" [appSwipeRight]="onSwipeRight"></main>',
})
export class GeneralComponent {
  // ...
  onSwipeRight() {
    this.router.navigate(['/myurl']);
  }
}

My Problem: The callback appSwipeRight includes a class variable router from the parent. This compiles fine, but when running, I get an error "Cannot read properties of undefined", since the variable is not present in the directive.

I found a workaround by injecting router: Router into the directive. But that´s pretty dirty, because it gets marked as unused (and I don´t want my directive to be specific).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can I pass router as a parameter of the callback or is there another way to fix this problem?

>Solution :

If you make the function an arrow function it will retain its original lexical context (ie. the this keyword will refer to the original context).

  onSwipeRight = () => this.router.navigate(['/myurl']);

Passing a normal function like you’ve done, this will refer to the new object that contains the function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading