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

Trigger Function on Input Change in Angular 2

Key aspects of component nesting: export class Child { @Input() public value: string; public childFunction(){...} } Main component responsibilities: export class Parent { public value2: string; function1(){ value2 = "a" } function2( ...

Difficulty Converting Array of Objects to Proper Type with Q.Promise and KO.mapping

I have encountered an issue while trying to filter an observable array. It seems that the ko.utils.arrayFilter method is converting all my model's field names to lowercase, causing unexpected behavior. I should mention that this project involves Types ...

Is there a way to determine if a string is empty, even if it contains hard returns?

I am currently working on a function that checks if a string is empty or not, but it seems to be missing the detection of new lines. export const isStrEmpty = function(text: string): boolean { return !text || text.match(/^ *$/) !== null; }; I attempted ...

Guidelines for cycling through a series of HTTP requests and effectively saving the data from each cycle into an array

Utilizing Spotify's API search feature, I am working with an array of SongSearchParams that consist of title and artist parameters: export class SongSearchParams { public title: string; public artist: string; constructor(title: string, a ...

In Angular 2, I am having trouble reaching the properties of an object nested inside another object

I have a variable named contact. When I used console.log(contact) to display its contents, this is what I got: addresss:[] company:"" emails:[] id:3 internet_calls:[] lat:"10.115730000000001" lng:"76.461445" name:"Diji " phones:[] special_days:[] timesta ...

Tips for utilizing single quotation marks while logging multiple variables in console

When I write console.log("entered values are "+A+" and "+B); the tsLint gives a warning that single quotes should be used. However, I discovered that if I use single quotes, I am unable to include multiple variables in the same console ...

Internal variable via router

The Back button on my main component is not always visible, depending on the child component. I have attempted to use a local variable with no success. In my parent app.component.html file, I have included the following: <button *ngIf="child.goBackUrl ...

Creating a personalized toolbar for Quill in your Angular project

Currently, I am developing a web application with Angular and aiming to incorporate Quill into it using the ngx-quill library available at here. One of my challenges involves creating a custom embed blot that displays unmodifiable text blocks fetched from ...

What is the reason for the removal of the `?` decorator in this mapped type? Are there alternative methods to achieve a similar outcome without eliminating it

Challenge In the process of creating a mapped type that excludes properties of type Function, we encountered an issue. Our current method not only eliminates functions but also strips away the optional decorator (?) from the mapped properties. Scenario ...

Detecting the upcoming click on the document using @HostListener in Angular 4 to dynamically generate a click listener

I'm currently working on a directive that toggles its state when clicked. The desired behavior is for the state to be deactivated if the user clicks anywhere else on the page while it is active. To achieve this, I attempted to use the Renderer2 liste ...

Simultaneous asynchronous access to a single object

I have been working with JS/TS for quite some time now, but the concept of race conditions still perplexes me. I am currently attempting to execute the following logic: class Deployer { protected txDataList: Array<TXData>; constructor() { this ...

What is the best way to invoke a function in a functional React component from a different functional React component?

I need to access the showDrawer method of one functional component in another, which acts as a wrapper. What are some best practices for achieving this? Any suggestions or insights would be appreciated! const TopSide = () => { const [visible, se ...

Troubleshooting Firebase functions that end with socket hang up error ECONNRESET

For the past two years, my Firebase Function has been successfully retrieving data from an external service with soap, parsing it, and sending it back to an Android app client. However, recently it suddenly stopped working without any changes on my part, g ...

A more concise approach to accessing a generic class method in Typescript

Let's analyze the code snippet below: export class BaseClass<T> { property = this.buildProperty(); buildProperty(){ return someBuilder<T>(); } } Through TypeScript, the type of property is automatically determined based on the ...

Enforcing Type Safety on String Enums in Typescript Using the 'const' Assertion

I am trying to use an enum for type checking purposes. Here is the enum I have: enum Options { Option1 = "xyz", Option2 = "abc" } My goal is to create a union type of 'xyz' | 'abc'. However, when I attempt to d ...

Angular CORS Policy

I encountered an issue when trying to send an authorization header JWT token from Angular. The error message reads: Access to XMLHttpRequest at 'http://localhost:52278/api/user/signup' from origin 'http://localhost:4200' has been blocke ...

Angular-cli does not come with the Bootstrap framework pre-installed

After installing the bootstrap framework to my angular2 project through npm, I noticed that it appeared in the node-modules folder. However, upon checking the angular-cli file, I discovered that the boostrap script and css were not included. "apps": [ ...

Combining user input with React's useState function

I have a form with three Quantity inputs. (Although more can be added dynamically, let's keep it simple for now and stick to three.) | - | - | Quantity | |---|---|----------| | - | - | 3 | | - | - | 4 | | - | - | 5 | Now, I want ...

TypeScript Error: The Object prototype must be an Object or null, it cannot be undefined

Just recently, I delved into TypeScript and attempted to convert a JavaScript code to TypeScript while incorporating more object-oriented features. However, I encountered an issue when trying to execute it with cmd using the ns-node command. private usern ...

The child module is unable to locate the route URL for the parent module

I'm new to Angular and I'm working on organizing my code into modules. So far, I have an admin module that responds to the /admin request, but now I want to add a child module called Portfolio Module. Everything is working fine, except for the f ...