I am currently facing an issue related to the length property. It is showing an ERROR TypeError: Cannot read property 'length' of undefined

Is it recommended to set the length to be inherited from Angular right? If so, why am I getting this error: "MyPostsComponent.html: 7 ERROR TypeError: Cannot read the 'length' of undefined property" when fileList.length is greater than 0?

onFileSelection(event){
  const fileList: FileList = event.target.filse;

  if (fileList.length > 0){
    const file: File = fileList[0];
    this.myFire.uploadFile(file).then(data => {
      //TO DO
      this.notifier.display('success','Picture Uploaded!');
      console.log(data['fileUrl']);
    })
    .catch(err => {
      this.notifier.display('error', err.message);
    });
  }
}

In my HTML code:

<input type="file" (change)="onFileSelection($event)" placeholder="Upload a file" accept=".png, .jpeg, .jpg">

Answer №1

const fileList: FileList = event.target.files;

It appears there is a small error in your code where you have filse instead of files, causing fileList to be undefined as an event's target does not have a property called filse.

Answer №2

If you want to modify your code, consider making the following adjustment...

const fileList: FileList = event.target.files || [];

I believe this change may be effective.

Answer №3

When fileList is null, it's important to include a null check like this:

if (fileList && fileList.length > 0){

Answer №4

The reason behind this issue is that your fileList variable is currently undefined. It's important to first ensure that the fileList is not undefined before proceeding.

onFileSelection(event){
      const fileList: FileList = event.target.filse;

      if (fileList && `enter code here`fileList.length > 0){
        const file: File = fileList[0];
        this.myFire.uploadFile(file).then(data => {
          //TO DO
          this.notifier.display('success','Picture Uploaded!');
          console.log(data['fileUrl']);
        })
        .catch(err => {
          this.notifier.display('error', err.message);
        });
      }
    }

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

Guide to implementing asynchronous REST API requests in Ionic 2

I'm working on an app for a school that allows students to scan their ID cards and enter. On the teacher's side of the application, I display the number of students present in each class. Currently, I am using a refresher to reload the page and u ...

The flexibility of adjusting the percentage in the ng-circle-progress feature

Currently, I am utilizing ng-cycle-progress in my Angular progress. Here is the HTML code: <circle-progress [percent]="score" [radius]="100" [outerStrokeWidth]="16" [innerStrokeWidth]="8" [outerStrokeColor]="'#78C000'" [innerStrok ...

What's New with Material 3 in Angular 17?

Even though I've taken the time to read all of the documentation at https://github.com/material-components/material-web/blob/main/docs/quick-start.md, I'm still struggling to figure out how to incorporate this into my Angular 17 project. I went ...

Challenges with image cropping in Angular causing performance problems

Utilizing this specific component for image cropping within an ionic/angular8 project has been causing severe performance issues, leading to unresponsiveness on mobile devices. Interestingly, the desktop version does not encounter any problems and the crop ...

The data retrieved from the web API is not undergoing the necessary conversion process

I am facing an issue with a web API call where the property checkNumber is defined as a double on the API side, but I need it to be treated as a string in my TypeScript model. Despite having the property defined as a string in my model, it is being receive ...

The 'type' property is not found on the 'never' type

There seems to be a typescript error showing up as Error: Property 'type' does not exist on type 'never' in the following code snippet: export const getSomething = (actionLog: [] | undefined) => { console.info(actionLog[length ...

Transmit a sequence of keys to the web browser

I'm having difficulty in sending a Shift key command followed immediately by tilde (~). I've attempted various examples, and here's one that I'm currently working on. I am testing the following scenario - selecting a specific image, t ...

What is the resolution process for importing @angular/core/testing in TypeScript and what is the packaging structure of the Angular core framework?

When using import {Injectable} from '@angular/core';, does the module attribute in package.json point to a file that exports injectable? Also, for the format @angular/core/testing, is there a testing folder within @angular/core that contains anot ...

The Angular Component utilizes the ng-template provided by its child component

I am currently facing an issue that involves the following code snippet in my HTML file: <form-section> <p>Hello</p> <form-section> <ng-template test-template> TEST </ng-template> ...

Navigating in Angular using a "complete URL" (URL with parameters) can be achieved with the following steps:

My search page is equipped with numerous filter options, all of which are included as parameters in the URL for easy sharing. When moving from the search results to a detailed view of an item, I pass the complete search result URL as a parameter (detail/1? ...

Modifying the Iterator Signature

My goal is to simplify handling two-dimensional arrays by creating a wrapper on the Array object. Although the code works, I encountered an issue with TypeScript complaining about the iterator signature not matching what Arrays should have. The desired fu ...

Despite the unconsumedBufferLength being 0, DataReader.loadAsync is still being completed

Working on UWP WinRT, I'm dealing with JSON stream consumption using the following code: async function connect() { let stream: MSStream; return new CancellableContext<void>( async (context) => { stream ...

What is the syntax for typing the router instance in Next.js?

I'm working on a password reset request form in my Next.js project. Here's the code I have: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } fro ...

Eliminate the unnecessary code repetition in my functions using Typescript

I have 2 specific functions that manipulate arrays within an object. Instead of repeating the same code for each array, I am looking for a way to create reusable functions. Currently, my functions look like this: setLists(): void { if (this.product.ord ...

Access the CSV file using Office365 Excel via a scripting tool

Objective I want to open a CSV file using Office365's Excel without actually saving the file on the client's machine. Challenge The issue with saving raw data on the client's machine is that it leads to clutter with old Excel files accumu ...

What is the proper way to utilize the router next function for optimal performance

I want to keep it on the same line, but it keeps giving me errors. Is there a way to prevent it from breaking onto a new line? const router = useRouter(); const { replace } = useRouter(); view image here ...

Inspecting an unspecified generic parameter for absence yields T & ({} | null)

Recently, I came across a perplexing issue while responding to this specific inquiry. It pertains to a scenario where a generic function's parameter is optional and its type involves the use of generics. Consider the following function structure: func ...

Initiate asynchronous ngOnInit

Can ngOnInit() actually return a promise? I've noticed a common practice where developers use this approach and it appears to be functional. However, there is a risk with unobserved promises as they can be resolved or rejected at unexpected times, s ...

What are the best ways to enhance change detection efficiency in Angular?

One issue I am facing involves two components and a service. It appears that when moving from the view of a routed component to elements in different components like a matMenu and an input field, the routed component seems to refresh itself. This becomes p ...

Outputting double columns with Typescript Sequelize associations

I am currently in the process of constructing table models using sequelize along with typescript. Here is an example of one of my models: 'use strict'; import { Model, InferAttributes, InferCreationAttributes, CreationOptional } from 'seque ...