Angular error: Attempting to access the value property of an undefined object

When attempting to delete a row from a table, an error occurred stating "TypeError: Cannot read property 'value' of undefined" after placing the delete button at the end of a row. I watched this video tutorial for guidance on deleting a row without loading its data into a form.

//service.ts
deleteProduct(key: string) {
  this.productList.remove(key);
}

//component.ts
onDelete(form: NgForm) {
  //deleteProduct() function
  if (confirm('Are you sure you want to delete this record?') == true) {
    this.ProductService.deleteProduct(form.value.$prdKey);
    //this.resetForm(form);
  }
}

onItemClick(prd: Product) {
  this.ProductService.selectedProduct = Object.assign({}, prd);
}
<!--the form-->
<form #productForm="ngForm" (ngSubmit)="onSubmit(productForm)">...</form>

<tr *ngFor="let product of productList">
  <td>{{product.prdName}}</td>
  <td><button type="button" class="btn btn-warning" (click)="onItemClick(product)" title="click to edit or delete" data-toggle="modal" data-target="#myModal">Update</button></td>
  <td><button type="button" class="btn btn-danger" *ngIf="ProductService.selectedProduct.$prdKey == null" (click)="onDelete(ProductService.selectedProduct.$prdKey)">Delete</button></td>
</tr>

I tweaked the code suggested in the video tutorial by changing

*ngIf="ProductService.selectedProduct.$prdKey == null"
instead of
*ngIf="ProductService.selectedProduct.$prdKey != null"
, so that the delete button will appear at the end of the row without needing to click on a specific row first. Any assistance in resolving this issue would be greatly appreciated. Feel free to ask for more snippets if necessary. Thank you in advance.

Answer №1

The reason for this issue is that in the onDelete() function, you are passing a key of type string, but the function definition expects it to be of type NgForm.

To fix this, change onDelete(form: NgForm) { to onDelete(key: string) {

Give this a try:

onDelete(key: string) {
  //function deleteProduct()
  if (confirm('Are you sure you want to delete this record?') == true) {
    this.ProductService.deleteProduct(key);
    //this.resetForm(form);
  }
}

Answer №2

give this a shot

//component.ts
onDelete(key: string) {
  //calling deleteProduct() function
  if (confirm('Are you sure to delete this record ?') == true) {
    this.ProductService.deleteProduct(key);
  this.productList.remove(key);
    //this.resetForm(form);
  }
}

Answer №3

There are numerous issues to address:

<button type="button" class="btn btn-danger" 
        *ngIf="ProductService.selectedProduct.$prdKey == null" 
        (click)="onDelete(ProductService.selectedProduct.$prdKey)">
            Delete
</button>
  1. ProductService.selectedProduct.$prdKey == null
    means the delete button is shown when $prdKey is null, resulting in always passing null to
    onDelete(ProductService.selectedProduct.$prdKey)

  2. onDelete(form: NgForm), you have set the parameter as NgForm, but you are getting null as explained above

  3. form.value.$prdKey this line will trigger an error

    TypeError: Cannot read property 'value' of undefined


You should instead use:

*ngIf="ProductService.selectedProduct.$prdKey != null"
as it makes more logical sense, and remove all products with $prdKey null.

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

Leverage the power of react-redux useSelector with the precision of TypeScript

When attempting to utilize the new useSelector hook (shown in the example below) from react-redux in TypeScript, an error is encountered indicating that the function does not exist: Module '"../../../node_modules/@types/react-redux"' has no expo ...

Guide to refreshing filters once data is updated in PrimeNG tables?

Whenever I add new rows to the table, the display updates dynamically. However, any filters I have applied only reflect the initial data. https://i.stack.imgur.com/5Nuxe.png For example, if I use the "startsWith" filter on a column labeled "Title" with a ...

Positioning CSS for a Responsive Button

Currently, I am working on making my modal responsive. However, I am encountering an issue with the positioning of the "SAVE" button. The button is not staying in the desired position but instead disappears. Below is the snippet of my HTML and CSS: .dele ...

The 'checked' property cannot be bound to 'mat-button-toggle' as it is not recognized as a valid property in Angular 9

I am encountering an issue with my Angular 9 application. I have integrated angular-material and imported the MatCheckboxModule correctly in the module. Here is the version of the material package I am using: "@angular/material": "^10.2.0&q ...

What is the best way to extract Angular's routing UrlMatchResult from UrlMatcher within a component?

Having trouble with routing in Angular 10. Trying to include a token in my URL that can contain various quantities of / characters. To prevent Angular routing from getting confused, I followed the advice on this post and decided to implement the UrlMatcher ...

Next.js Troubleshooting: Unexpected Issue with 'use client' Triggering Error in React Client Component

Keeping it simple, here is a useState function that I am using: 'use client' import {useState} from 'react'; const Home = () => { const [fruit, setFruit] = useState('apple'); return ( & ...

Utilizing arrayUnion function in Firestore with Angular

My journey to learn Firestore has hit a roadblock. The documentation on AngularFire and FieldValue hasn't been much help. Every time I try to use FieldValue, it throws an error saying "FieldValue does not exist." const userRef = this.firestore.collect ...

Ways to establish the relationship between two fields within an object

These are the definitions for two basic types: type AudioData = { rate: number; codec: string; duration: number; }; type VideoData = { width: number; height: number; codec: string; duration: number; }; Next, I need to create a MediaInfo typ ...

Beware of the 'grid zero width' alert that may appear when utilizing ag-Grid's sizeColumnsToFit() function on multiple ag-Grids that are shown within a tab menu

Encountering a warning message when resizing ag-Grid and switching between tabs. The warning reads: ag-Grid: tried to call sizeColumnsToFit() but the grid is coming back with zero width, maybe the grid is not visible yet on the screen? A demo of this ...

Navigating to a component that also needs to redirect

I have a main feature (let's call it "main hub") that houses various sections. Within the "main hub" feature, I navigate to another section (let's call it "subsection") which also contains different subsections. In one of these subsections, call ...

The issue with the React Hook for window resize not updating remains unresolved

I have a React Hook designed to update the window size on resize, but it's not functioning correctly. Can someone please help explain why this is happening and provide guidance on how to utilize this hook in another component to create a Boolean value ...

The incorrect sequence of Angular/Protractor functions is causing issues within the tests

Trying to extract the values from a column in a grid and compare them before and after sorting can be tricky. I have two functions set up for this task - one to retrieve the initial column values, and another to check the order post-sorting. However, there ...

Cannot establish a connection with Socket.IO

I've encountered an issue with establishing a connection to Socket.IO in my node server. Although the server starts successfully with Socket.IO, I am not seeing any console logs when trying to connect to Socket. this.server.listen(this.port, () => ...

What is the function of the OmitThisParameter in TypeScript when referencing ES5 definitions?

I came across this specific type in the ES5 definitions for TypeScript and was intrigued by its purpose as the description provided seemed quite vague. /** * Removes the 'this' parameter from a function type. */ type OmitThisParameter<T> ...

A guide on incorporating unique font weights into Material UI

Looking to customize the Material theme by incorporating my own font and adjusting the font weights/sizes for the Typography components. I am attempting to set 100/200/300/400/500/600/700 as options for each specific typography variant, but it seems that o ...

Issues arise when attempting to override attributes within the HTML of a parent component in Angular

Why does overriding an attribute in a child class that extends from another not work as expected? Here's a made-up scenario to simplify the issue: Parent class file: gridbase.component.ts import { Component, OnInit } from '@angular/core'; ...

Tips for populating class attributes from an Angular model

Suppose there is a Class Vehicle with the following properties: public id: number; public modelId: number; public modelName: string; Now consider we have an object that looks like this {id: 1, modelId: 1, modelName: "4"} What is the best way to assign e ...

Can you explain the correct method for assigning types when destructuring the `callbackFn.currentValue` in conjunction with the `.reduce()` method? Thank you

I'm working with an array of arrays, for example: const input = [['A', 'X'], ['B', 'Y'],...]; In addition to that, I have two enums: enum MyMove { Rock = 'X', Paper = 'Y', Scis ...

The mat-select choices are experiencing rendering issues

This is the HTML code I am using to display select locations and a map below it: Here is the HTML code for the above view, <mat-form-field class="locationSelector"> <mat-select placeholder="Choose location" (ngModel)="ServiceLocations"> ...

Enhanced hierarchical organization of trees

I came across this code snippet: class Category { constructor( readonly _title: string, ) { } get title() { return this._title } } const categories = { get pets() { const pets = new Category('Pets') return { ge ...