user5363995 user5363995 - 5 months ago 83
AngularJS Question

Angular 2 reference class member from within audio nativelement event method

I have the following class and I am trying to reference the selectedSong object from within the onplay event of the native element. Is there a way to do this? In Angular 1.x you could use $scope... etc..

export class PlayerComponent implements AfterViewInit {
@ViewChild('myAudio') myAudio: any;

selectedSong: Song;

ngAfterViewInit() {
let audio = this.myAudio.nativeElement;
audio.onended = function () {
console.log("song ended");
//get handle to selected song NOT working as "this" refers to the audio object
let s = this.selectedSong;
}
}
}

Answer

That's caused by function. Use arrow functions instead:

ngAfterViewInit() {
    let audio = this.myAudio.nativeElement;
    audio.onended = () => {
        console.log("song ended");
        //get handle to selected song NOT working as "this" refers to the audio object
        let s = this.selectedSong;
    }
}

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions