Exploring Several Images and Videos in Angular

I'm experiencing a challenge with displaying multiple images and videos in my Angular application. To differentiate between the two types of files, I use the "format" variable.

Check out Stackblitz

export class AppComponent {
  urls;
  format;

  onSelectFile(event) {
    const files = event.target.files;
    if (files) {
      for (const file of files) {
        if (file.type.indexOf("image") > -1) {
          this.format = "image";
        } else if (file.type.indexOf("video") > -1) {
          this.format = "video";
        }

        const reader = new FileReader();
        reader.onload = (e: any) => {
          this.urls.push(e.target.result);
        };
        reader.readAsDataURL(file);
      }
    }
  }
}

Answer №1

The variable urls exists but has not been initialized, causing an error when trying to push elements into an undefined variable. To resolve this issue, make sure to initialize the variable as follows:

urls = [];

Update: Create separate arrays for images and videos, then iterate through them using a loop:

export class AppComponent {
  imageUrls = [];
  videoUrls = [];
  onSelectFile(event) {
    const files = event.target.files;
    if (files) {
      for (const file of files) {
        const reader = new FileReader();
        reader.onload = (e: any) => {
          if (file.type.indexOf("image") > -1) {
            this.imageUrls.push(e.target.result);
          } else if (file.type.indexOf("video") > -1) {
            this.videoUrls.push(e.target.result);
          }
        };
        reader.readAsDataURL(file);
      }
    }
  }
}

To display the images and videos, use the following code:

<ng-container>
    <img *ngFor="let url of imageUrls" [src]="url" />
</ng-container>

<ng-container>
    <video *ngFor="let url of videoUrls" [src]="url" controls></video>
</ng-container>

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

Discovering all instances of a particular name in JSON using incremented values: a guide

I am looking to automatically detect every occurrence of a specific name in my JSON data. { "servergenre": "Classic Rock", "servergenre2": "pop", "servergenre3": "rock", "servergenre4": "jazz", "servergenre5": "80s", "serverurl": "http://www.n ...

Implement JQuery to include a screensaver on your website

My website in asp.net c# displays the performance of a specific process on an LCD TV screen. The data is refreshed every 15 seconds using the code below: <div id="InfoTop"> <table width="100%" cellpadding="0" cellspacing="0"> ...

Obtain the coordinates of the pixel in an image on the canvas when a mouse

I am currently working on a project that involves using canvas. I have set a picture as the background of the canvas and would like to be able to get the original pixel point when clicking in the image area. In order to achieve this, I need to convert canv ...

tips for creating a unique component with specialized features

I am struggling to integrate action buttons with specific actions in my custom component. It seems challenging to provide functions to my custom table, especially those that depend on the attributes of the table itself. You can take a look at this exampl ...

At compile time, Typescript runs smoothly, but errors may arise during runtime

Currently, I am delving into learning Typescript and have encountered a snag in my code. Despite searching extensively for a solution, I have been unable to find any relevant material pertaining to my issue. Below is the code snippet in question: <code ...

Discovering the final step of a for loop when working with JavaScript objects

Currently, my data consists of: {12: Object, 13: Object, 14: Object} I need help figuring out how to detect the final iteration in the for loop below: for (var i in objs){ console.log(objs[i]); } Does anyone have any solutions? ...

Can you recommend a technology similar to WebSockets that does not rely on a framework like Node.js?

I am currently developing a basic betting game and I want to enhance the user experience by updating values in real-time. The challenge is that most of my application is written in jQuery and JavaScript, with a MySQL database set up by a different develo ...

Using Lodash library to iterate through a collection using the _.forEach method

Currently, I am attempting to implement the lodash forEach method within a structure where a nested function is being used to call a mongo database. var jobs = []; _.forEach(ids, function(id) { JobRequest.findByJobId(id, function(err, result) { ...

Save the test outcomes in HTML format using cypress

Can Cypress test results be exported to an HTML or another format, similar to cucumber-report.html? ...

I possess a pair of UI tabs. Whenever a button located outside the tab is clicked, I am required to activate a distinct tab

As a beginner in Javascript, I recently encountered an issue with a UI tab element that contains two tabs. My goal is to create a button that, when clicked, will scroll up and activate the second tab. <style> .tab-container { overflow-x: ...

Combining a table to create a JSON object with an array attribute

I am currently working with two SQL tables that have a one-to-many relationship. The query for this data is being requested by my node.JS server and I need to parse the information into a specific JSON format. For each repeated row, I want to insert the da ...

Using ReactJS to create cross-browser inline styling with flexbox

I'm currently working on a React web application that relies heavily on inline styling. My goal is to ensure compatibility with the latest versions of major browsers (Safari, Chrome, Firefox, IE) while utilizing flexbox for layout. The issue I encou ...

Undefined Response Error when Utilizing Dropzone for File Upload in Express

I am currently in the process of setting up a basic image upload demonstration using Dropzone and Express. Here is what my form looks like: <form id="ul-widget" action="/fileupload" class="dropzone" enctype="multipart/form-data"> <div class="fal ...

Problem with lazy loading in Angular nested routing

My application requires the sign-in functionality to be available at startup, with all other code lazy loaded after authentication. I've set up a core module consisting of a core-routing module and a core component to manage this process. However, the ...

Generate a <mat-error> element dynamically and ensure it is correctly projected into the parent <mat-form-field> component

Creating a component dynamically using the ComponentFactoryResolver is relatively simple, but I have encountered an issue when attempting to project the created component into its parent when working with the Angular Material <mat-error> component in ...

Instructions for validating an input field with yup to ensure it does not begin with '-', '+', or '_'

Is there a way to validate user input using YUP and restrict values that begin with '-', '+', or '_'? Thank you for your help! name: Yup.string() .required() .min(5, 'Too short') .matches(/^[aA-zZ&bso ...

AngularJS allows you to toggle the visibility of a div at set intervals, creating

I am struggling with the task of showing and hiding a div that serves as an alert for my application. Currently, I am using $interval to create a continuous show and hide action on the div. However, what I aim for is to have the DIV visible for X amount o ...

Tips on converting Nextjs generated Prisma types case from snake_case to camelCase

I have a full-stack application built with Next.js and Prisma ORM "next": "12.3.0" "prisma": "^4.5.0" Essentially, I am looking to convert the case of my types from snake_case to camelCase to align with the front-en ...

What is the functionality of the getBlock('meta') method within DocPad?

While transitioning a website from a different site generator to DocPad, I am currently exploring the capabilities of the getBlock('meta') feature. Understanding how to utilize getBlock('scripts') and getBlock('styles') was re ...

Angular-powered dynamic data table component fails to render data sources in display

Currently, I am deep in the process of mastering Angular. I've been developing a versatile table component that can be utilized across my entire application. I have successfully configured the columns and pagination settings. Everything looks correct ...