Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ngafterviewinit, @viewchild element is undefined

Tags:

angular

@ViewChild('videoPlayer') myVidElement: ElementRef;

I have html5 video elemnt in markup with view child as above

that element is not becoming accessible, it is logged undefined both in ngOnInit & ngAfterViewInit method

My goal is to extract video duration , code is as follows

 ngAfterViewInit(): void { 
   console.log("after view init -- " + this.myVidElement); 
   this.eventsService.videoLengthInSeconds = this.myVidElement.nativeElement.duration; 
 }

html as follows

<div fxLayout="row" fxLayoutAlign="space-between start" 
    class="ats-analyzer ats-p-t-10" *ngIf=" currentParticipant">    
  
  <div fxFlex="45%" class="ats-analyzer--video ats-p-r-10">         
    <video controls #videoPlayer>
      <source [src]="atsAnalyzerVideoUrl" type="video/mp4">         
    </video>
  </div>

</div>

I have read, it won't be available in ngOninit, but not able to understand why it is not acceble in ngAfterViewInit().. your help is appreciated

like image 704
sp14 Avatar asked Oct 15 '25 04:10

sp14


1 Answers

Your ViewChild is still undefined in ngAfterViewInit because it isn't created yet at that time. This belongs to the wrapping *ngIf around it since it is only created as soon as the currentParticipant has been set to a truthy value.

Based on your comment I assume that the currentParticipant is set after a HTTP request or another async operation.

Let assume your code to get the currentParticipant looks like this

ngOnInit() {
  this.someService.getCurrentParticipant().subscribe((currParticipant) => {
    this.currentParticipant = currParticipant;
  });
}

In this case, your ViewChild becomes only available after an execution of the subscription where a truthy value is written to currentParticipant.

To make your example working where you want to write the duration of the video to a service you have 2 options:

  1. Use ViewChildren because then you can listen to changes (docs)

  2. You can use setter/getter on your ViewChild and update your service in the setter

You can find more information here.

like image 141
Batajus Avatar answered Oct 17 '25 21:10

Batajus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!