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

Encountering a type error while trying to read dummy data, as the map function is not

I am currently working on fetching dummy data from a URL in my component using TS and Next.js. Unfortunately, I encountered an error type that I am unable to diagnose. typings.d.ts: export type Themen = { id: number; title: string; description: string; ...

Interactive Angular Interfaces Featuring Numerous Numeric Choices Within the Main Object

I am currently in the process of designing an interface for my Angular project that allows users to search for video games using the WhatToPlay API within RapidAPI. When a user searches for details on a video game, the result will return a game identified ...

Creating a personalized Autocomplete feature using React Material-UI with the help of the renderInput method

I'm currently using a React Material UI Autocomplete component, similar to the one in the official documentation. For example, let's consider a list of countries: import * as React from 'react'; import Box from '@mui/material/Box& ...

Converting an array of object keys into integers only can be done using JavaScript

Here is an array of objects with various nutrients and their values: [ {nutrient: "Energy", per100: "449kcal", per35: "157kcal", id: 6} {nutrient: "Fat", per100: "24.4g", per35: "8.6g", id: 1} {nutrient: "Saturated fat", per100: "4.5g", per35: "1.6g ...

Customizing the appearance of the Material UI MuiClockPicker with unique style

I am wondering how I can override the styles for MuiClockPicker? I discovered that using createTheme to override the styles actually works for me, but I encountered an error from TypeScript: TS2322: Type '{ MuiOutlinedInput: { styleOverrides: { roo ...

Get your hands on the latest version of Excel for Angular

214/5000 I am currently facing an issue in Angular where I am attempting to generate an excel file. Within the file, there is a "Day" column that is meant to display numbers 1 through 31. However, when attempting this, only the last number (31) is being pr ...

I am encountering a "TypeError: topics.forEach is not a function" error when attempting to retrieve metadata for topics using my kafkajs client in Node.js/express.js. Can anyone help me understand why

I am attempting to retrieve the metadata of my Kafka brokers' topics using the kafkajs admin client within my Node.js + express.js server. Here is the content of my index.js file, serving as the main entrypoint for npm: 'use strict'; cons ...

Limiting the display of every item in Angular ngFor

I'm currently working with Angular and I have the following code in my component.html: <div class="card" *ngFor="let item of galleries;" (mouseenter)=" setBackground(item?.image?.fullpath)" (mouseover)="showCount ...

Button click does not fill in Jquery Datepicker?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <link type="text/css" href="Styles/Site.css" rel="Stylesheet" ></link > <script type="text/javascript" src= ...

Browser not reflecting changes made to Angular 2 code

Currently facing a challenging issue with my express/angular2 app. Despite using nodemon and seeing the Express code updating fine, I am experiencing issues where my components and services are not updating when I reload the page in the browser. Even aft ...

The process of HTML compilation is halted due to the unexpected presence of the forbidden 'null' data type, despite the fact that null cannot actually be a valid value in

Encountering an issue with my HTML code, where the compiler stops at: Type 'CustomItem[] | null | undefined' is not compatible with type 'CustomItem[] | undefined'. Type 'null' cannot be assigned to type 'CustomItem[] ...

Utilizing interpolation in Angular to apply CSS styling to specific sections of a TypeScript variable

Suppose I have a variable called data in the app.component.ts file of type :string. In the app.component.html file, I am displaying the value of data on the UI using string interpolation like {{data}}. My question is, how can I apply some css to specific ...

Gulp encountered an issue - Module 'sigmund' not found

After installing browser-sync, my previously working Gulp encountered an error: Error: Cannot find module 'lru-cache' To resolve this issue, I utilized the following solution: npm link lru-cache as suggested in this thread However, upon atte ...

Is there a different method I can utilize to create a conditional statement for assigning a value in JavaScript?

I have this code snippet that seems a bit unclear to me: if (!app.config.admin.examStatusId) { app.config.admin.examStatusId = exam.examStatus.dataPlus[0].id; } Do you have any suggestions on how I could rewrite this more clearly without using an if s ...

Behaviorsubject has a circular relationship

I have a situation where I am monitoring changes in a behaviorSubject and then modifying the data before updating the behaviorSubject with the updated information. This seems to create a loop. What would be a more effective approach for handling this sce ...

What is the best way to trigger an AJAX request when a user navigates away from a webpage or closes the

The Challenge at Hand Greetings, I am currently developing a database-driven game that involves users answering questions and earning the right to change the question by providing the correct answer. However, I have encountered a significant issue which ...

Issue with checkboxes preventing submission of form

Currently working on a website project for a company that requires certain steps to be completed for deliveries. Unfortunately, I am facing issues with the submit button, and I apologize as I am still new to this. The code I have pasted is divided into tw ...

Adjusting the empty image source in Vue.js that was generated dynamically

Currently experimenting with Vue.js and integrating a 3rd party API. Successfully fetched the JSON data and displayed it on my html, but encountering issues with missing images. As some images are absent from the JSON file, I've saved them locally on ...

Different approaches to transforming jQuery code into functional AngularJS code

I am a beginner in AngularJS and I'm looking to implement functionality for a login page similar to the one you see when you click the 'Forgot Password' link: Would it be more appropriate to use a directive instead of a controller for this ...

Leveraging angular.forEach for JSON Iteration

In my app and controller, I am working on creating a "flow chart style" question and answer system. To keep track of the current question and answer, I am using variables like $scope.ActiveQuestion and an array named $scope.ActiveAnswers. I am struggling ...