Deleting a particular item in Angular involves utilizing specific techniques for removal, while updating a

After connecting my reactive form app with a REST API, I encountered an issue while trying to delete a hotel. Instead of displaying the ID of the clicked hotel, it shows "Really delete the Hotel: (undefined)?" What could be causing this problem in my code and how can I resolve it?

Below is the code for the delete function:

    deleteHotel(): void {
    if (this.hotel.ID === 0) {
    // Don't delete, it was never saved.
    this.onSaveComplete();
     } else {
    if (confirm(`Really delete the Hotel: ${this.hotel.hotelName}?`)) {
    this.hs.deleteHotel(this.hotel.ID)
    .subscribe(
      () => this.onSaveComplete()

    );
    }
   }
   }

And here is the .html form:

  <form  (ngSubmit)="onSubmit(rHotelForm)" [formGroup] = "rHotelForm">
  <input type="hidden" formConrolName="id"/>
<div class="form-group">
    <div class="form-group col-md-6">
      <label >Hotel Name</label>
      <input id="hotelNameId" class="form-control" type="text" 
     formControlName="hotelName"/>

    </div> 

    <div class="form-group">
        <div class="form-group col-md-6">
          <label >Phone</label>
          <input class="form-control"formControlName="phone">
        </div> </div>


                <div class="form-group">
                    <div class="form-group col-md-6">
                      <label >Number of rooms</label>
                      <input class="form-control" formControlName="numberOfRooms" >
                    </div> </div>

                      <div class=" col-md-6">
                        <button  type="submit" class="btn btn-lg btn-block btn-info" [disabled] ="!rHotelForm.valid">Submit</button>
                      </div> 
                      <div class=" col-md-6">
                          <button class="btn btn-lg btn-block btn-secondary" (click) ="resetForm(hotelForm)">Reset</button>
                        </div> 






</form> 
<br> Value : {{rHotelForm.value | json}}
  <form [formGroup] = "hotelForm">

   <ul><li *ngFor="let hotel of hotels">

    <span>
        <a class="btn" (click)="deleteHotel()">
        Hotel ID :{{hotel.ID}} Hotel Name : {{hotel.hotelName}} 
   </a>
      </span>

</li></ul>
<button class="btn btn-lg btn-block btn-secondary" (click) 
 ="deleteHotel(hotel.ID)">Delete Hotel</button>
  </form>

Answer №1

It seems from the code provided that there is an issue with deleting a hotel. The delete function is not receiving the specific hotel to be deleted, resulting in an undefined error.

<ul><li *ngFor="let hotel of hotels">

    <span>
        <a class="btn" (click)="deleteHotel()">
        Hotel ID :{{hotel.ID}} Hotel Name : {{hotel.hotelName}} 
   </a>
      </span>

</li></ul>

deleteHotel(): void { }

To resolve this issue, update the code as follows:

<ul><li *ngFor="let hotel of hotels">

        <span>
            <a class="btn" (click)="deleteHotel(hotel)">
            Hotel ID :{{hotel.ID}} Hotel Name : {{hotel.hotelName}} 
       </a>
          </span>

    </li></ul>
 deleteHotel(hotel): void {
    if (hotel.ID === 0) {
    // Don't delete, it was never saved.
    this.onSaveComplete();
     } else {
    if (confirm(`Really delete the Hotel: ${hotel.hotelName}?`)) {
    this.hs.deleteHotel(hotel.ID)
    .subscribe(
      () => this.onSaveComplete()

    );
    }
   }
   }

Answer №2

When I tried replacing the deleteHotel() function with getHotel(hotel.ID) and then introducing a new delete hotel method, it actually worked.

Here is the code snippet for the getHotel method:


getHotel(id: number) {
  this.hs.getHotel(id).subscribe(
    hotel => this.hotel = hotel,
  );
}

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

Problems encountered while attempting to transition from Angular 8 to Angular 9

I'm currently following Angular's official updating guide to upgrade from version 8.0 to 9.0, but I've encountered a problem that I can't seem to find any relevant information on when researching online. Upon completion of the update p ...

Error: The module 'AppModule' has encountered an unexpected value 'CalendarComponent'. To resolve this issue, please include a @Pipe/@Directive/@Component annotation

Recently, I started working with Angular 2 and wanted to incorporate the 'schedule' feature from Primeng. To do so, I installed its package and added the calendarComponent in my app.module.ts file as shown below: import { BrowserModule } from &a ...

The ViewChild property encountered an error: "The child element cannot be found"

I am facing an issue in Angular 7 where I have a parent component with a child component. I would like to obtain a reference to the child component within the parent component so that I can access its functions and properties. Child Component : @Componen ...

Angular2 implementation of scroll spy feature for CKEditor

I have a file loaded in CKEditor with a side menu located outside the editor. I'm looking to dynamically highlight specific items in the side navigation as different sections of the document are scrolled through. details.component.ts focusFunction() ...

Creating an endless scrolling feature with Ionic 3

My tech stack includes symfony3 and FosRestBundle for the backend, and Ionic 3 for the frontend development. While attempting to implement an InfiniteScroll feature following the Ionic documentation, I encountered an issue where only the loading text and ...

What is the process for changing the border color of a material selection?

Is it possible to customize the border color of a material select element? I attempted changing the border color using css from: https://i.sstatic.net/mw9jq.png to this: https://i.sstatic.net/8b7w7.png Any suggestions on how to achieve this? Appreciate an ...

Is there a way to implement error validation successfully in React Hook Form while utilizing template literals within the register function?

Utilizing React Hook Form along with Typescript, I am in the process of constructing a series of forms using a configuration object. Within this configuration object, there exists a key named prop which is of type string and is being passed to the register ...

Avoiding caching of GET requests in Angular 2 for Internet Explorer 11

My rest endpoint successfully returns a list when calling GET, and I can also use POST to add new items or DELETE to remove them. This functionality is working perfectly in Firefox and Chrome, with the additional note that POST and DELETE also work in IE ...

Using git mv in VSCode does not automatically adjust TypeScript / JavaScript import paths

Is there a way to successfully move a typescript file in VSCode to achieve both of the following: Ensure Git acknowledges the file continuity Have VSCode update the parent files' import statements I have tried two methods, but each one falls short: ...

What advantages does using an RxJS Subject have over handling multiple event listeners individually in terms of speed

After investigating a page's slow performance, I identified an angular directive as the root cause. The culprit was a piece of code that registered event listeners on the window keydown event multiple times: @HostListener('window:keydown', ...

Unexpected lack of error in Typescript intersection type and function signature

I have defined the following data structures: type SampleA = { a: string; } type SampleB = { b: number; } type SampleC = { c: boolean; } type Samples = SampleA & SampleB & SampleC; Next, I utilize the defined types in the f ...

Using dictionary keys as valid property values

I have put together a dictionary like so: const iconTypesDictionary: { [key: string]: IconPrefix } = { solid: 'fas', regular: 'far', light: 'fal', } My goal is to be able to utilize the keys of this dictionary as potent ...

Typescript is throwing a Mongoose error stating that the Schema has not been registered for the model

I've dedicated a lot of time to researching online, but I can't seem to figure out what's missing in this case. Any help would be greatly appreciated! Permission.ts (This is the Permission model file. It has references with the Module model ...

Combine and modify an object coming from a different component

Recently, I developed a customized viewer component specifically designed to showcase song sheets. One of my main objectives is to give users the ability to adjust font settings and other display preferences at their discretion. In order to accomplish this ...

Optimizing Performance in Firebase Cloud Functions - Defining Functions for Efficiency

Currently, I am organizing the code in my index.ts by creating simple line function definitions like: HTTP Example export const demoHttpApp = functions.https.onRequest( (req, resp) => new DemoHttpClass(req, resp).run() ); Real-Time Database Example ...

Angular project is showing a unique error that says '$localize' is undefined according to Eslint

I successfully implemented localization in my Angular 15 project. However, I encountered an issue with linting for .ts files: error '$localize' is not defined no-undef Here's the configuration in my .eslintrc.json file: { "root": true, ...

This error message in AngularJS indicates that the argument 'fn' is not being recognized as a function

I am currently working with angularjs and typescript and I am attempting to create a directive in the following manner: Below is my controller : export const test1 = { template: require('./app.html'), controller($scope, $http) { ...

Tips for transforming a string into a date using Angular

What is the best way to transform a string into a date in Angular13? Here's an example: str = '2022-06-09T22:00:00Z'; needs to be converted to a datetime format of mm/dd/yyyy --:-- -- ...

Having trouble applying CSS styling to the div element

I'm new to CSS and struggling with aligning content within a div. Specifically, I can't get the actual price (striked off) to display next to the discounted price in the card - it keeps appearing underneath. Any ideas on how I can improve my CSS ...

Is there a way to avoid waiting for both observables to arrive and utilize the data from just one observable within the switchmap function?

The code snippet provided below aims to immediately render the student list without waiting for the second observable. However, once the second observable is received, it should verify that the student is not enrolled in all courses before enabling the but ...