Angular 5 throwing an error - trying to access a property that is undefined

In my form, each div contains a label, checkbox, and input field. When the menu is opened, all checkboxes are initially unchecked, disabling all input fields. You can then enable an input field by checking its corresponding checkbox.

I attempted to implement a solution from a Stack Overflow question, but encountered an error regarding an undefined array. The first checkbox (index [0]) functions correctly, but subsequent checkboxes do not.

Below is the code snippet:

ngOnInit() {
    this.resetValues();
    .......... 
    ...... 
    ... 
}
    
resetValues() {
    this.checkboxArr = [
        { name: 'disabledDegree', disabled: true },
        { name: 'disabledEmployedTo', disabled: true },
        { name: 'disabledEmploymentType', disabled: true },
        { name: 'disabledSelOrg', disabled: true },
        { name: 'disabledSelMan', disabled: true }
    ];
    ....... 
    ..... 
    .. 
}
    
checkSelected(name: string) {
    console.log('name', name);
    this.checkboxArr.forEach((x: any) => {
        if (x.name === name) {
            x.disabled = !x.disabled;
        }
    });
    console.log('loop', this.checkboxArr);
}
<div class="inner" *ngIf="checkboxArr && checkboxArr.length"> <-- the addition of this ngIf did not resolve the issue.
<div class="row">
    <div class="label-column">
        <label for="DegreeOfEmployment">...</label>
        <input type="checkbox" id="DegreeOfEmploymentCheckBox" name="DegreeOfEmploymentCheckBox" (change)="checkSelected(checkboxArr[0].name)">
    </div>
    <div class="input-column target-org-unit">
        <input [disabled]="checkboxArr[0].disabled" id="DegreeOfEmployment" name="DegreeOfEmployment" type="text" value="">
    </div>
</div>
<div class="row">
    <div class="label-column">
        <label for="EmployedTo">....</label>
            <input type="checkbox" id="EmployedToCheckBox" name="EmployedToCheckBox" (change)="checkSelected(checkboxArr[1].name)">
        </div>
        <div class="input-column target-org-unit">
            <input [disabled]="checkBoxArr[1].disabled"  id="EmployedTo" name="EmployedTo" type="date" value="">                            
        </div>
    </div>
    <div class="row">
        <div class="label-column">
            <label for="EmploymentType">....</label>
            <input type="checkbox" id="EmploymentTypeCheckBox" name="EmploymentTypeCheckBox" (change)="checkSelected(checkBoxArr[2].name)">
        </div>
        <div class="input-column target-org-unit">
            <input [disabled]="checkBoxArr[2].disabled" id="EmploymentType" name="EmploymentType" type="text" value="">                            
        </div>
    </div>
</div>

Answer №1

When working with Angular/JavaScript/TypeScript, remember that it is case sensitive even though HTML is not. Make sure to use either checkBoxArr or checkboxArr, but do not mix them in your TypeScript/JavaScript or HTML files.

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

When working with Typescript, it is important to correctly identify elements as checkboxes in order to avoid any red underlines when referencing

When trying to check the input type of an element, such as a checkbox in TypeScript, I encounter the issue of the 'element.checked' property being underlined in red. The code snippet below shows how I attempt to address this: element: HTMLElemen ...

Looping through NavItems component using JavaScript or Angular

My Angular project includes a navbar component with an app sidebar that has a navItems attribute. Below is the content of my navBar: <app-header style="background-color : #e65100;" [fixed]="true" [navbarBrandFull]="{ src: &a ...

The attribute 'inventory' cannot be found in the declaration of 'WarehouseModule'

I am facing an issue with my AngularFire setup. I have recently installed the latest version of AngularFire using npm i @angular/fire and have successfully configured Firestore. However, when attempting to load data into my Firestore database, I encounte ...

Find with user-friendly input/label removal function (Ionic 2)

I have embarked on creating a recipe application where users can search for recipes by ingredients. I want to enhance the functionality of the search feature so that when users press the spacebar to enter the next input, it appears as a label below with an ...

Troubleshoot TypeScript API within Angular 12 using Chrome debugger

I'm having trouble finding a solution on SO. Can anyone help me debug and check the code snippet below for hello? getHero(): void { const id = parseInt(this.route.snapshot.paramMap.get('id') !, 10); this.heroService.getHero(id) .sub ...

What is the best way to position Scroll near a mat row in Angular?

With over 20 records loaded into an Angular Material table, I am experiencing an issue where clicking on the last row causes the scroll position to jump to the top of the page. I would like the scroll position to be set near the clicked row instead. Is th ...

typescript Can you explain the significance of square brackets in an interface?

I came across this code snippet in vue at the following GitHub link declare const RefSymbol: unique symbol export declare const RawSymbol: unique symbol export interface Ref<T = any> { value: T [RefSymbol]: true } Can someone explain what Re ...

How to send a variable to Firestore query in an Angular application

I'm attempting to retrieve data from a schedule collection based on a field matching the user's id. However, I'm encountering an issue with the error message: "Function Query.where() requires a valid third argument, but it was undefined." ...

Extract data from an HTTP request and assign it to variables using filter and map in Angular

I need to extract data from an http get request and assign it to 3 separate variables once fetched. Data: [ { reportId: 1, results1: [{ name: "TotalReferralsMade", optionId: 3082, factor: 1, description: null ...

What is the best way to implement an EventHandler class using TypeScript?

I am in the process of migrating my project from JavaScript to TypeScript and encountering an issue with transitioning a class for managing events. To prevent duplicate option descriptions for adding/removing event listeners, we utilize a wrapper like thi ...

Regular pattern with Kubernetes cluster endpoint utilizing either IP address or fully qualified domain name

In my Angular/typescript project, I am working on building a regex for a cluster endpoint that includes an IP address or hostname (FQDN) in a URL format. For instance: Example 1 - 10.210.163.246/k8s/clusters/c-m-vftt4j5q Example 2 - fg380g9-32-vip3-ocs.s ...

Test fails in Jest - component creation test result is undefined

I am currently working on writing a Jest test to verify the creation of a component in Angular. However, when I execute the test, it returns undefined with the following message: OrderDetailsDeliveryTabComponent › should create expect(received).toBeTru ...

Leverage TypeScript generics to link props with state in a React class-based component

Can the state type be determined based on the prop type that is passed in? type BarProps = { availableOptions: any[] } type BarState = { selectedOption: any } export default class Bar extends React.Component<BarProps, BarState> { ...

@nestjs - JwtModule.registerAsync is failing to register in a timely manner, resulting in unresolved dependencies

Encountering some challenges with the registerAsync function in combination with JwtModule and JwtService. While browsing various discussions, it seems like many were stuck on ConfigModule, but that's not a part of my project. Let me provide some con ...

What is the reason behind TypeScript's decision not to raise an error in case of a mismatched function argument type?

Here's a simple illustration to showcase my point: type Info = { id: number; } type ImportantInfo = { id: number; value: 5; } type Task = (data: Info) => void; const task: Task = data => null; const data: ImportantInfo = { i ...

Changing a date format in typescript: Here is how you can easily convert a date from one

Using React with Typescript: I am currently working with a date picker from material-ui version 5. The date picker requires the date value to be in the format "yyyy-MM-dd". However, the API returns a Date object in the format "2022-01-12T00:00:00.000+00:0 ...

Error in cypress configuration occurs when a plug is mistakenly defined as an import instead of a const within the cypress.config.ts file

Hello, I am new to using Cypress so please bear with me if this seems like a trivial issue. Below you will find my cypress.config.ts file where I am attempting to integrate the cypress esbuild preprocessor into the configuration. import cypress_esbuild_pre ...

Utilizing NextJS to efficiently route requests directly to the backend and send the responses back to the client within the

In the technology stack for my project, I am using a Next.js server for the front end and a separate back-end server to handle user data storage. When a client needs to send a request to the back end, they first make an API request to the Next.js server, ...

The canActivate function must be responsive to the true or false value of this.authService.isLoggedIn before proceeding

I am facing a problem with my app's routing functionality. When the user logs in with their Google email, I want the app to route to the home page: "". Everything seems to work fine except for the canActivate routeGuard. During the AuthLogin ...

Angular: "btn" class vanishes when the button is toggled

I am facing an issue with the button's class change functionality. I am using the [ngClass] directive to switch between Bootstrap classes for the button style. However, when I click the button, the "btn" class seems to disappear from the code. Instead ...