Unidentified file: Error reading property 'filename'

I have a function that retrieves the file name.

The file name is displayed in an input field, but the background color of the input field is only visible when a file is selected and the file name is populated there.

I would like the background color to be visible regardless of whether there is a value present or not.

Initially, it looked like this:

<input * ngIf = "items.length> 0" type = "text" [(ngModel)] = "items [0] .filename" class = "form-control Input-Metadata">

I want to change it to:

<input * ngIf = "items.length>= 0" type = "text" [(ngModel)] = "items [0] .filename" class = "form-control Input-Metadata">

However, when I implement this change, I encounter the following error: Cannot read property 'filename' of undefined.

Could someone provide assistance?

component.ts

for (let index = 0; index < files.length; index++) {

        const item: any = {
          filename: event.target.files[index].name.split('.')[0],
          fileType: event.target.files[index].type.split("image/").join(""),
          fileSize: event.target.files[index].size,
        };

        this.filename = item.filename;
        this.fileType = item.fileType;
        this.fileSize = item.fileSize;
        this.items.push(item);

        const reader = new FileReader();
        reader.onload = (e: any) => {
          item.url = e.target.result;
          const image = new Image();
          image.src = e.target.result;
          image.onload = function () {
            item.sizeH = image.width;
            item.sizeV = image.height;
            self.sizeH = item.sizeH;
            self.sizeV = item.sizeV;
          };

        }
        formData.append('file', files[index]);
        reader.readAsDataURL(files[index]);
      }

Answer №1

Modify the *ngIf statement as follows:

<input *ngIf = "data.length > 0" type = "text" [(ngModel)] = "data[0].name" class = "form-control Input-Data">

Answer №2

Here is a possible solution:

<input * ngIf = "items.length>= 0" type = "text" [ngModel]="items && items[0]?.filename" (ngModelChange)="items?.length && items[0].filename=$event" class = "form-control Input-Metadata">

This code snippet was inspired by this helpful response

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

"NODEJS: Exploring the Concept of Key-Value Pairs in Object

I am facing a challenge with accessing nested key/value pairs in an object received through a webhook. The object in req.body looks like this: {"appId":"7HPEPVBTZGDCP","merchants":{"6RDH804A896K1":[{"objectId&qu ...

What is the best way to parse JSON data with Typescript?

I am dealing with JSON data structured as follows: jsonList= [ {name:'chennai', code:'maa'} {name:'delhi', code:'del'} .... .... .... {name:'salem', code:'che'} {name:'bengaluru' ...

Tips on hiding the menu toggler in PrimeNg

Struggling with PrimeNg implementation in my Angular project, I am unable to find a simple solution to hide the menu toggler. Allow me to illustrate my current setup in the first image and what I desire in the second. Let's dive in: View First Image ...

Disabling lint in a PhpStorm or WebStorm project with angular-cli

I am currently using PhpStorm version 2017.2, and I have created an angular-cli project within a directory that already contains several modules and components built with angular-cli. The issue I am facing is that I am inundated with countless linting err ...

Using React TypeScript: maximize the efficiency of sending multiple JSON objects to the frontend with the useData hook

Currently, I am experimenting with a customized useData hook based on the React Beginner course by CodingWithMosh. This modified hook contains multiple objects within it. In the original course content, all data was stored in the results JSON object. I am ...

Creating eight equal sections within HTML <div> elements using Bootstrap

I am brand new to Angular. I need to design something like this: https://i.sstatic.net/Zcb9i.png However, I'm struggling to find the right solution. Here is what I have so far: https://i.sstatic.net/7hsrk.png. Having been a backend developer, I&ap ...

Encountering a hiccup with dependencies during the transition to Angular 9 with jodit-angular

Encountering the following error when attempting to execute the command npm install after migrating Angular to version 9. Error npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-pro ...

What is the process for setting up a callback function in material-angular-select?

It's surprising that I couldn't find an onselect callback for the material-angular-select component. How can I create a callback for it? Here is my attempt: import { Component, Input, Output, OnInit, OnChanges, SimpleChanges, ChangeDetectionStr ...

Error: In Angular 4, there is an issue where trying to access the length property of an undefined property results in a

How to Fix TypeError: Cannot Read Property 'length' of Undefined in Angular 4 This is the code snippet that is causing the error: export class UserComponent implements OnInit{ roles:IUserRole[]; sourseRoles: SelectedItem[]; selectedRole:a ...

I am encountering difficulty accessing my index.html file located in the views directory. Whenever I try to access it through localhost 3000, I receive an error message saying "cannot get"

My files are available for viewing on github at https://github.com/elmoreka/myTaskLIst.git. I'm experiencing issues with my index.html file located in the views directory. When trying to access localhost 3000, I receive an error stating "cannot get". ...

Issue with Nativescript Angular router version 3.0.0-alpha.7 causing navigation errors

This project example highlights a problem: https://github.com/rrcoolp/test-router-app/ Issue with navigation: The test project showcases an issue with NATIVESCRIPT ANGULAR 2 (RC3) and Nativescript router 3.0.0-alpha.7. The problem is straightforward - na ...

Sending HTML content to viewChild in Angular 5

I'm struggling to figure out how to pass HTML to a ViewChild in order for it to be added to its own component's HTML. I've been searching for a solution with no luck so far. As a newcomer to Angular, many of the explanations I find online ar ...

Unable to assign a value to a constant within the class constructor

I'm aware that in TypeScript, readonly properties can only be assigned a value within a class constructor. However, I encountered an error while trying to do so inside the constructor of my class, specifically related to an array method handler. class ...

Execute the function once Router.navigate is completed

Is there a way to execute a specific function after a user successfully logs in, regardless of which page they logged in from? The goal is to redirect the user back to their previous browsing page upon login. I've been using Router.navigate for URL r ...

How can I merge these two Observables in Angular to create an array of objects?

Let's say we are working with two different datasets: student$ = from([ {id: 1, name: "Alex"}, {id: 2, name: "Marry"}, ]) address$ = from([ {id: 1, location: "Chicago", sid: 1}, {id: 2, location: &qu ...

A guide on creating a concatenation function using TypeScript

Looking for a way in Typescript to define an interface Calculator that allows for concatenation capabilities? interface Calculator { ... } let calcu: Calculator; calcu(2).multiply(5).add(1) I attempted the following: interface Calculator { (num: n ...

The deletion of property '1' from the [object Array] is not possible

How to Retrieve a List in My Components Using Input : @Input() usersInput: Section[]; export interface Section { displayName: string; userId: number; title: number; } Here is the Value List : 0: displayName: "بدون نام" ...

Determining the typing of a function based on a specific type condition

I have created a unique type structure as shown below: type Criteria = 'Criterion A' | 'Criterion B'; type NoCriteria = 'NO CRITERIA'; type Props = { label?: string; required?: boolean; disabled?: boolean; } & ( | ...

Is it possible to utilize CreateSpyObj to generate a spy for every method within a given class?

I am in the process of creating unit tests for my Angular application and I am exploring the usage of spies. Currently, for each service utilized by my component, I find myself writing code similar to the following: let fakeMyService = jasmine.createSpyO ...

Consider the presence of various peer dependency versions in a react-typescript library

Currently, I am in the process of converting my react component library react-esri-leaflet to typescript. This library requires the user to install react-leaflet as a peerDependency and offers support for both react-leaflet version 3 (RLV3) and react-leafl ...