4

I have a component to show a video. To access the video in .ts-File I use @ViewChild and get it as a ElementRef, but i need it as a HTMLVideoElement. I can't figure out, which lifecycle hook is the best for casting.

I tried to make the casting in ngOnInit and ngAfterViewInit, but get Problems, because I use it in ngOnChange and it is called before and therefore still undefined. So obviously it would work to cast it in ngOnChange, but I actually want to cast it only one time and not on every change. My working solution right now is, just to use only the ElementRef-Element, but I don't like it, because everywhere I have to write videoplayerNativeElement.nativeElement

@ViewChild('videoplayer') private videoplayerNativeElement: ElementRef;
private videoPlayer: HTMLVideoElement;

public ngOnInit() {
  //wrong place for 
  //this.videoPlayer = this.videoplayerNativeElement.nativeElement;
}

public ngAfterViewInit(): void {
  //wrong place for 
  //this.videoPlayer = this.videoplayerNativeElement.nativeElement;
}

public ngOnChanges(): void {
  //do stuff with videoPlayer, like videoPlayer.play()
}

I would expect there must be a good place for making the casting, but can't figure out where.

Giannis
  • 1,790
  • 1
  • 11
  • 29
SAM
  • 742
  • 10
  • 24
  • Check this answer: https://stackoverflow.com/questions/43111474/how-to-stop-ngonchanges-called-before-ngoninit – Gordon Mohrin Oct 24 '19 at 09:44
  • You could create a function with the stuff like play() and call it in OnChanges only if videoPlayer has a value and call the same function in AfterviewInit with ChangeDetectorRef.detectChanges() like this? https://stackblitz.com/edit/video-angular-el – Marcel Hoekstra Oct 24 '19 at 10:58

0 Answers0