Which Angular lifecycle hook is the right one to cast ElementRef?

Viewed 311

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.

0 Answers
Related