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

The method of having two consecutive subscribe calls in Angular2 Http

Can the Subscribe method be called twice? I am attempting to create an API factory that stores data in the factory and allows different components to use that data for each AJAX call. The factory: export class api { result = []; constructor (p ...

Problem with ngStyle: Error indicating that the expected '}' is missing

I encountered an error in the Chrome console when trying to interpret the code below: <div [ngStyle]="{'width': '100%'; 'height': '100%'; 'background-size': 'cover'; 'background-repeat&ap ...

Is it possible to pass a parameter to an NGXS action that is not the Payload?

I am working on implementing an Ngxs action that includes a parameter in addition to the payload. This parameter is used to determine whether or not a notification should be sent. @Action(UpdateUser) async UpdateUser( ctx: StateContext<ProfileStat ...

Adding a separator for thousands on data labels in ng2-charts

Take a look at this demonstration: http://embed.plnkr.co/7fGsiuRjcF0M0Ffeoml2/ If I modify the data to be: data: [2000, 3000, 4000, 8000, 12000, 12850] Can I add thousand separators to the dataset label? For example: 5,000 10,000 15,000 ...

When executing the command "ng serve" in Angular, the following error is displayed: "webpack: Compilation failed."

I am currently using Mac OS (10.11.6) and have been attempting to familiarize myself with Angular. I successfully installed node.js, typescript, and angular-cli, and everything seemed to be functioning properly. However, whenever I executed "ng serve", it ...

Method for Injecting Global Constants Provider in Angular 2

I am trying to implement a global constants setup in my Angular app, specifically with a root directory that should be accessible to every component without the need for manual imports. I came across a solution on Stack Overflow suggesting the use of a con ...

The specified module could not be located in the ngx-toastr library

I'm having trouble finding the solution... ERROR in ./node_modules/ngx-toastr/fesm5/ngx-toastr.js Module not detected: Error: Unable to locate '/Users/vasanthan/Mean projects/node_modules/@angular/animations' in '/Users/vasanthan/Mean ...

I'm having trouble getting Remix.run and Chart.js to cooperate, can anyone offer some guidance?

I've encountered a challenge with Remix.run and chart.js (react-chartjs-2) when attempting to display the chart. I followed the documentation and installed the necessary dependencies: react-chartjs-2 and chart.js. Here's the snippet from my pac ...

What is the best way to link the value of a mat-slider to an input field in a reactive form?

Is there a way to synchronize the min and max values of a ranged mat-slider with corresponding input fields? Currently, when I set numbers in the input fields, the slider updates correctly. However, when I use the slider to change the value of the input fi ...

Traverse through an array of objects with unspecified length and undefined key names

Consider the following object arrays: 1. [{id:'1', code:'somecode', desc:'this is the description'}, {...}, {...}] 2. [{fname:'name', lname:'last name', address:'my address', email:'<a h ...

What is the best way to integrate model classes within an Angular module?

I have a few classes that I want to keep as plain bean/DTO classes. They are not meant to be display @component classes, @Pipe classes, or @Directive classes (at least, that's what I believe!). I am trying to bundle them into a module so that they ca ...

Unable to connect to Alpine store from an external source due to a typescript error

Here is how I have configured my Alpine store: Alpine.store( 'state', ({ qr: '' })) Now, I am attempting to update it from an external source as follows: Alpine.store( 'state' ).qr = 'test' However, I am encounte ...

Navigating a webpage with Material select and routerLink in Angular 6

I am currently developing a feature that allows users to navigate to a page to access a list of documents from a policy. In addition, I am incorporating all policies so that users can easily move between them using a select form and direct you to the selec ...

Encountering an issue while trying to import the validator module in NextJS 13

I encountered a peculiar issue while trying to import a module. Nextjs presented the following error message: ./application/sign_in/sign_in_store.ts:2:0 Module not found: Can't resolve 'validator' 1 | import { createEvent, createStore } fr ...

The use of URL embedded parameters in @angular/http

Currently, I am utilizing a backend system that accepts search query parameters in both the ?-notation and the url-embedded format. I understand that I can use tools like URLSearchParams/RequestOptionsArgs to send requests to . However, I am curious about ...

Discover the data type of the subfield within an interface or type in Typescript

Check out the interface and type declarations provided below: interface Foo { bar: { a: number b: string } } type Foo = { bar: { a: number b: string } } Is it possible to obtain the type definitions for "baz"? This will allow us ...

DatePipe incorrectly displays date format

I am currently working with Angular version 12 and using datePipe.transform. I have a date in the format dd/MM/yyyy as a string, and I want to bind this date into my reactive form for editing. The reactive form includes an Angular Material date picker comp ...

What is the best way to protect an Angular/Spring application using Keycloak?

I am seeking to enhance the security of my Spring Boot (backend) and Angular (frontend) application by implementing Keycloak for authentication. Currently, I have a simple deployment setup where the executable jar created by Spring serves both the backend ...

What is the correct way to import scss files in a Next.js project?

Currently, I am working on a NextJS project that uses Sass with TypeScript. Everything is running smoothly in the development environment, but as soon as I attempt to create a build version of the project, I encounter this error. https://i.stack.imgur.com ...

Loading screen displayed while transitioning between routes within Angular

I have been struggling to implement a loading spinner in my project. How can I display a loading screen when changing routes in Angular? Here is the HTML code snippet: <div *ngIf="showLoadingIndicator" class="spinner"></div> ...