Oops! The program encountered an issue where it was unable to access the properties of an undefined variable, specifically while trying to

When creating a custom validation function in Angular, I encountered an issue where using a variable within the validation would result in an error: "ERROR TypeError: Cannot read properties of undefined (reading 'file')". This occurred when changing the value in the form. The custom extension file for validation required me to declare and assign a value to the variable inside it. I am trying to understand why this error is happening. Could it be that the custom validate function is not observing changes and executing before other functions? Why does the variable value not exist and end up being assigned to undefined? Also, how can I use the file size in the validate file size function? Below is the component code:

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { AbstractControl, FormArray, FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { PagedResult } from 'src/app/core/models/pagedResult.model';
import { AlertService } from 'src/app/core/services/alert.service';
import { FakeDataService } from 'src/app/core/services/fake-data.service';
import { Employee } from '../../models/employee.model';
import { PenaltyReason } from '../../models/penalty-reason.model';
import { PenaltyType } from '../../models/penalty-type.model';
import { Penalty } from '../../models/penalty.model';

@Component({
  selector: 'app-penalties',
  templateUrl: './penalties.component.html',
  styleUrls: ['./penalties.component.css']
})
export class PenaltiesComponent implements OnInit {

  penalties: PagedResult<Penalty>;
  page = 1;
  formTitle = "اضافة عقوبة";
  penaltyTypes: PenaltyType[];
  penaltyReasons: PenaltyReason[];
  employees: Employee[];
  selectedPenaltyIndex: number;
  penaltyForm: FormGroup;
  file: FormControl;

  constructor(private fakeData: FakeDataService, private alert: AlertService) { }

  loadData() {
    this.fakeData.getDataFor('Penalties', this.page).then(result => {
      this.penalties = result as PagedResult<Penalty>;
    });
  }

  // Other component methods...

}

Answer №1

Here is an example of how you can utilize this:

Within the component file:

 handleFileInput(files: any) {
    this.fileNameDetail = undefined;
    const image = files.files.item(0);
    const reader = new FileReader();
    reader.addEventListener("load", () => {
      this.imageUrl = reader.result;
    }, false);
    reader.readAsDataURL(image);
  }

Within the template file:

 <button (click)="filePicker.click()" class="file-picker-opener">Select File</button>
  <input type="file"
         class="form-control"
         #filePicker
         accept="image/jpeg,image/jpg"
         id="file"
         (change)="handleFileInput($event.target);"
  />

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

Create type declarations using the Typescript compiler by running the command:

After generating my definition file ".d.ts" using tsc --declaration or setting declaration as true in the tsconfig.json, I noticed that the generated files are missing declare module "mymodule" {... } This appears to be causing issues with "tslint" which ...

Is there an alternative method to retrieve model value on controller in Angular bootstrap ngbdatepicker since the (change) method has been removed?

Currently, I am working with ngbdatepicker in Bootstrap. I have added a datepicker selector to appcomponent.html and the datepicker is showing up. Now, I need to retrieve that model value into the controller so that I can pass it to the parent appcomponent ...

Guidelines for adjusting the next/image component to a full 100% height

In my Next.js application, I am trying to display an image that fills the full height of its container while automatically adjusting its width based on its aspect ratio. I attempted the following method: <Image src="/deco.svg" alt=&qu ...

Transform the object into an array of JSON with specified keys

Here is a sample object: { labels: ["city A", "city B"], data: ["Abc", "Bcd"] }; I am looking to transform the above object into an array of JSON like this: [ { labels: "city A", data: "Abc" }, { labels: "city B", data: "Bcd" }, ]; ...

Creating a link with a POST method and without using a new line

I am attempting to generate a square matrix and send data using the post method. I have discovered a solution involving JavaScript and form submission, but each time a new form is created, it results in a new line being added. Alternatively, if I move th ...

What is the TypeScript syntax for indicating multiple generic types for a variable?

Currently working on transitioning one of my projects from JavaScript to TypeScript, however I've hit a roadblock when it comes to type annotation. I have an interface called Serializer and a class that merges these interfaces as shown below: interfa ...

Using TypeORM in Javascript to create routes efficiently

After examining the TypeORM websites examples, I noticed that some of them demonstrate routing usage using TypeScript. Given that TypeORM has the capability to use JavaScript instead of TypeScript, I am seeking guidance on how to implement Express routing ...

Tips for verifying that a file has not been selected in Croppie

Whenever I use croppie to crop images on my website, everything works fine when I select an image and upload it. But if I try to crop and upload without selecting an image, a black image gets uploaded instead. How can I validate if the file upload is empty ...

Unable to perform a POST request and send JSON data using AJAX with jQuery at the

It seems like there may be a server issue causing this problem, and unfortunately, I don't have access to our server to troubleshoot. I was hoping that someone else might have a solution or could help me understand the root cause of the issue. The is ...

Utilizing Angular to make API requests and handle promises

Currently, I am facing a challenge in my angular application which involves working with the soundcloud api. The issue arises when I make a call to the soundcloud api to retrieve my tracks, loop through them to extract the iframe embed object, inject it in ...

Understanding the integration of jQuery html attributes with Angular2

I am encountering an issue with a library that requires me to include the tag below in my image: data-zoom-image When I add this tag to my image: <img class="larger-picture" [src]="'images/'+item.picture" align="middle" data-zoom-image="&ap ...

Encrypting data between two Node.js servers

I am looking to create a Node.js daemon that can operate across multiple computers while facilitating message exchange between the daemons. Security is paramount, so I want to ensure the communication is encrypted. However, I am uncertain about which encry ...

An error is being thrown by SetState when included within componentDidmount

I am currently learning React JS and have started working on a small application using it. I'm encountering an issue with the SetState method inside the componentDidMount lifecycle method. The scenario is that I have a parent/home component, which ca ...

Issues with previewing PDF files in AngularJS

I am trying to display a PDF preview on my website using the following code: var $scope; angular.module('miniapp', ['phonecatFilters', 'ngSanitize']); function Ctrl($scope) { $scope.test = 'Example from: '; ...

Encountering a "self is not defined" error while utilizing the Jodti-React text editor within a Next.js project

Issue with 'self is not defined' error while using jodti-react in a Next.js project import React, { useState, useRef, useMemo } from "react"; import Dashborad from "./Dashborad"; import JoditEditor from "jodit-react" ...

The subsequent code still running even with the implementation of async/await

I'm currently facing an issue with a function that needs to resolve a promise before moving on to the next lines of code. Here is what I expect: START promise resolved line1 line2 line3 etc ... However, the problem I'm encountering is that all t ...

Updating the styles of React Native components using stylesheets

I've created a unique React component with the following structure: import { StyleSheet } from 'react-native'; import { Input, Item } from 'native-base'; import Icon from 'react-native-vector-icons/FontAwesome'; import { ...

Send the user to a customized dashboard depending on their user role permissions using Vue.js

Currently, I am developing a system that involves handling multiple role-permissions for users. To provide some context, there are 3 distinct users in this scenario: User1 (customer), User2 (employee), and User3 (admin). For each of these user types, I ha ...

Tips for testing Sequelize with Jasmine

In my database/index.ts file, I set up a Sequelize database using the code below: import { Sequelize } from 'sequelize'; const { DATABASE_DIALECT, DATABASE_HOST, DATABASE_PORT, DATABASE_USER_NAME, DATABASE_USER_PASSWORD, DATABASE_NAM ...

What could be causing the "AJAX data not defined" error

Attempting to make an Ajax post request to the root directory on my Express server. By simply using the HTML form and submitting an artist name, I successfully receive a response back and can send the information to the client without any issues... As se ...