Exploring Angular: How to implement a listener to detect when data (such as a video) is loaded and trigger actions

I'm currently working on displaying a video in my Angular page and I'm trying to set the currentTime property of the video to start playing at a specific time.

In JavaScript, you can achieve this with the following example:

document.getElementById("video").addEventListener(
  "loadedmetadata",
  (e) => {
    e.target.currentTime = 50;
  },
  false
);

However, I am facing issues setting the startTime in my Angular application.

My HTML code looks like this:

<video
        id="lecture-video"
        controls
        #video
        (timeupdate)="onVideoChange($event)"
      >
        <source [src]="videoUrl" />
      </video>

And here is the TypeScript code:

@ViewChild('video') video!: ElementRef;

ngAfterViewInit():void {
     console.log(this.video.nativeElement);
     console.log(this.video.nativeElement.currentTime);
}

While it works fine in Stackblitz, it doesn't work in my project. However, if I add a setTimeout function like this:

setTimeout(()=>{
console.log(this.video.nativeElement.currentTime)
}, 3000)

Then it does work. So my main question is: How can I wait or add a listener that will execute when the video is loaded?

Check out the Stackblitz example for reference: https://stackblitz.com/edit/angular-ivy-z5dzvg?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts

Thank you in advance for your help!

Answer №1

There was just one error in your code. Instead of using ViewChildern, you should be using ViewChild.

import { AfterViewInit, ElementRef, OnInit, ViewChild } from '@angular/core';

@ViewChild('video') video!: ElementRef;

By making this change, you will be able to access your video element in the console.


-------------------Updated----------------------------

Make sure to implement AfterViewInit in your component class.

export class AppComponent implements OnInit, AfterViewInit { ... }

Utilize ViewChild to retrieve the element.

@ViewChild('video') video: ElementRef;

Then use the video variable to access the element.

ngAfterViewInit(): void {
   console.log('video', this.video.nativeElement);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 2: Despite changes in property, ElementRef.nativeElement.offSetwidth consistently returns the same value

Recently, I encountered an HTML element that caught my attention: <h1 [style.font-size.em]="mysize" id="title-text" #titleText>{{ screenInfo.title }}</h1> This particular element piqued my curiosity because the variable "mysize" controls the ...

The Typescript interpreter failed to load because the module 'ts-node/register' could not be found

I am facing an issue with my Node.js API deployed using pm2. After deployment, I encounter the following error: Failed to load Typescript interpreter: Cannot find module 'ts-node/register' Require stack: - /usr/local/lib/node_modules/pm2/lib/Pro ...

Module not found when attempting to import a newly created TypeScript module

A fresh Typescript project called puppeteer-jquery has just been released on the NPM registry. The code is functioning perfectly well. However, when attempting to integrate it into another project: npm install puppeteer-jquery and trying to import it lik ...

How to define a variable in Angular Module and make it accessible in all components?

Is it possible to declare a variable in my app.module and access it from child components without having to declare it again or using global injection? Curious to know if this can be done! ...

Navigating through an array's contents with RxJs

Is there a more efficient way to iterate over an array fetched from an observable using RxJS operators in order to generate and emit new individual ListingItem objects? onGetItemData(){ this.dataService.getItemData().subscribe((itemData) => { this.it ...

One convenient file for displaying toast notifications, alerts, and loaders specifically designed for the most recent version of Angular

I have been working on a design pattern that involves creating code for various informative widgets such as toast, alert, popup, and loader. My question is where in the angular directory structure should this pattern be placed, and is this approach correc ...

The @HostListener in Angular2 does not function correctly within a component that is inherited from another component

My Angular2-based client-side application has a base class: abstract class BaseClass { @HostListener('window:beforeunload') beforeUnloadHandler() { console.log('bla'); } } and two similar derived classes: @Component({ ...

Following the update of Angular, a "process is not defined" error message appears

After successfully upgrading our Angular 7 app to Angular 12 using the migration steps from the official Angular website, we encountered a warning when running the Angular CLI with npm start: 'node-sass' usage is deprecated and will be removed in ...

How can you automate the execution of unit tests in Angular before pushing changes to Git?

There have been instances in Angular projects where the unit tests are triggered every time a build is carried out, as well as when running the git push command. In case any tests fail during either of these commands, the process halts until all unit tes ...

What is the best way to assign a value to an option element for ordering purposes?

My select element is being populated with fruits from a database, using the following code: <select name="fruitsOption" id="fruitsOptionId" ngModel #fruitRef="ngModel"> <option *ngFor="let fruit of fruits">{{fruit}}</option> </selec ...

Types are not appearing in @types/node

I have added @types/node to my project. In the index.ts file, the default node modules are being treated as type any. const fs = require('fs'); The type of fs is currently set to any. { "ts-node": { "cwd": "/User ...

When Android build APK is released, HTTP requests fail, yet they work seamlessly during debugging

While debugging, all API calls function correctly. However, when creating a build apk file, the requests are not being called in the build apk. Despite having an SSL certificate on the server, the request still fails to go through. ...

Obtaining the ViewRef of the current component in Angular 4

How can I obtain the ViewRef for my current component? I am attempting to retrieve the ViewRef from a service. Below is the code: component.service.ts import { Injectable, ViewRef } from '@angular/core'; @Injectable() export class CheckboxSe ...

Tips for synchronizing object updates between parent and child components in React applications

I have a dilemma with my 2 components: The parent component looks like this: @Component({ selector: 'parent', template: ` <child [obj]="obj"> </child> `, styleUrls: [''], }) export class ParentComponent impleme ...

Dialog component from HeadlessUI doesn't support the Transition feature

Currently working with Next.JS version 14.1.3 I recently integrated the <Dialog> component from HeadlessUI and configured TailwindCSS. However, I encountered an issue where the Modal window doesn't have any transition effects even though I foll ...

What is the method to obtain the complete URL in Angular?

I'm exploring ways to utilize Angular Universal in my app and I am seeking a method to retrieve the complete path of the current url within an Angular component. Initially, I considered tapping into the window object which would involve injecting it o ...

In search of assistance with resolving a React Typescript coding issue

I need help converting a non-TypeScript React component to use TypeScript. When attempting this conversion, I encountered the following error: Class 'Component' defines instance member function 'componentWillMount', but ext ...

Transform AngularJS service into Angular service

I am looking for guidance on how to migrate from AngularJS to Angular. I have a component called ForgotPassword and I am unsure of the correct method to send an http.post request to my C# controller. function (window, angular) { "use strict"; angular.m ...

I want to display a background color using this ng-template

enter image description hereMy code includes an ng-template that uses ngFor to generate internal HTML tags without the ability to add CSS properties. <ng-template *ngFor="let c of colors" contextMenuItem let-item (execute)="change_task_color($event.ite ...

What's the reason behind my REST API delivering a 401 error code?

New Update After being encouraged to implement debug logs, I have discovered that the issue lies with Spring reporting an invalid CSRF token for the notices controller. I have compared the headers generated by Postman and the fetch requests, but found no ...