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 [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).
Can I pass router
as a parameter of the callback or is there another way to fix this problem?
CodePudding user response:
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.