Add the item to the array and then use the *ngFor directive to iterate

Whenever the addRoom button is clicked, I want to add an object to an array. The problem is that the data in my array keeps getting repeated. Please excuse any language errors in my explanation. Feel free to ask me for clarification in the comments below. Thanks for taking the time to read this!

Here is my code:

<table class="booking-table">
<tr>
    <th>ROOM</th>
    <th>5 + YRS</th>
    <th>0-5 YRS</th>
    <th>PER NIGHT</th>
</tr>
<tr *ngFor="let item of Room">
    <td>{{item.room}}</td>
    <td>
        <select [ngModel]="item.audutModel" (ngModelChange)="AddAdults($event)">
            <option value="1">
                1 Adults
            </option>
            <option value="2">
                2 Adults
            </option>
            <option value="3">
                3 Adults
            </option>
        </select>
    </td>
    <td>
        <select [ngModel]="item.childModel" (ngModelChange)="AddChild($event)">
            <option value="1">
                1 Child
            </option>
            <option value="2" *ngIf="this.Adults == 1 || this.Adults == 2">
                2 Child
            </option>
            <option value="3" *ngIf="this.Adults == 1">
                3 Child
            </option>
        </select>
    </td>
    <td>{{item.pricePN}}</td>
</tr>
<button type="" (click)="AddRoom()">add room</button>

Typescript code:


  AddAdults(Adults){
    this.Adults = Adults;
    console.log(this.Adults)
    this.pricePerAd = 200;
    this.price = 1000 + Adults*this.pricePerAd;

  }

  AddChild(child){
    this.pricePerCh = 100;
    this.price += child*this.pricePerCh;


  }



 AddRoom(){
  
    this.audutModel = "audut";
    this.childModel = "child";
    this.RoomNumber = this.RoomNumber + 1 ;

    this.audutModel =   this.audutModel + this.RoomNumber;
    this.childModel = this.childModel + this.RoomNumber;


   this.object.room = this.RoomNumber;
   this.object.audut = this.audutModel;
   this.object.child = this.childModel;
   this.object.pricePN = this.price;

   this.Room.push(this.object)
}

}

Answer №1

Every instance of the this.object is being used consistently, implying that all items in the array are identical. To differentiate them, each item needs to be unique.

Here's a basic example that requires further refinement and development. It's important to follow naming conventions, like using rooms = [] instead of Room = []. Consider creating an Interface for the Room model as well.

When adding a new room, initialize an empty object and increment a local variable called idx, which corresponds to the index in the array. After adding a room, increase this index:

addRoom(){
  this.rooms.push({room: this.idx+1, adult: null, child: null, pricePN: null})
  this.idx++;
}

In your template, utilize two-way binding for adding adults (or children) without the need for a separate function. Instead, call calculate when changes occur, passing the index (i) declared during the iteration on rooms:

<select [(ngModel)]="item.adult" (change)="calculate(i)">

The calculate function calculates the total cost based on the number of adults and children for a specific room:

calculate(index) {
  this.rooms[index].pricePN = 
        1000 + this.rooms[index].adult * 200 + this.rooms[index].child * 100;
}

You can simplify your code by removing unnecessary variables, keeping only the declaration of the array.

Feel free to experiment with this setup by checking out the DEMO.

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

Tips for iterating through nested objects with a for loop

Struggling with validations in an Angular 5 application? If you have a form with name, email, gender, and address grouped under city, state, country using FormGroupname, you might find this code snippet helpful: export class RegistrationComponent implemen ...

Having trouble choosing multiple options from autocomplete drop-down with Selenium web-driver in Python

I am currently in the process of automating a webpage built with Angular that features an auto-complete dropdown with numerous elements. My goal is to click on each individual element and verify if it populates all the fields below accordingly. Below is th ...

Tips for creating a table in Angular 2

I need help creating a new row in a table using Angular. I know how to do it in pure Javascript, like the code below where addRow() method is called to generate a new row. But I'm new to Angular and want to learn the correct way to achieve this withou ...

Utilizing lodash and Angular 8: Identifying an valid array index then verifying with an if statement

In my current project, I am developing an e-commerce angular application that includes a basket with two types of products: restaurant + show combos and gift cards. When a client reserves a restaurant, they must also reserve a show; conversely, the client ...

Can you explain the reference to "ng2" in relation to Angular 2?

In countless blog posts discussing Angular 2, I often come across references to ng2. Can someone clarify what ng2 stands for? Is it the CLI for Angular 2? ...

Utilizing Angular 2's ViewChild within the <router-outlet> Tag

I've been working on a project using Angular 2. Within the MainComponent, I'm utilizing @ViewChild to reference child components. The MainComponent also contains a <router-outlet> where various components are loaded. My query is, how can I ...

Leveraging Google Analytics with Angular 4 and beyond

Having trouble integrating Google Analytics with Angular 4? Can't seem to find the @type for ga.js in ts? Here's a quick fix that I implemented in every component: declare let ga: any; How did I solve it, you ask? I created a function to dyna ...

Is it possible for dynamically created components to trigger output events?

My objective: Dynamically create components (completed) Enable dynamically created components to utilize "outputs" so that parent Components can listen for changes from the children. Here is a Plnkr showcasing what I am trying to achieve: Plnker -> htt ...

Passing dynamic values to nested components within an ngFor loop in Angular

I'm currently facing an issue with a child component inside a ngFor loop where I need to pass dynamic values. Here is what I have attempted so far, but it doesn't seem to be working as expected <div *ngFor="let item of clientOtherDetails& ...

Getting the local path of a file from an input file in Angular 7

Is there a way to retrieve the local file path from an input field in HTML? After running the code below, I obtained 'C:\fakepath\fileTest.txt' I am looking for a method to get the local path so that I can pass it on to my control ...

What is the predefined value for a multi-select generated by the ng-for directive in Angular?

I am having trouble setting default selected values for the multi-select. Despite trying various methods such as initializing the ngModel to bind the variable and using [selected] = "selectedSegment == 'S1'", none of them seem to be effective fo ...

Encountering issues with Angular2 forms while working with JavaScriptServices/Universal

My Angular2 app was built using the JavaScriptServices starter from GitHub. The issue I'm encountering is a runtime error when I include a form in a component. Both FormsModule and ReactiveFormsModule are being imported. This is how my form is stru ...

Guide on entering text into an Angular input field with Selenium in Python after navigating tabs

After switching tabs, I am attempting to enter text into an Angular input field. However, I keep encountering the following errors: AttributeError: 'tuple' object has no attribute 'send_keys' or ElementClickInterceptedException or NoS ...

When the query result is received in Angular TypeScript, translate epoch time into a time string

Here is the dilemma I am currently facing: I have an Angular script that requests data from a backend service and receives query results to display to the user. One of the fields in the query response is a time stamp, which is currently in epoch time forma ...

Creating Angular models for complex nested JSON structures

I'm a beginner with Angular and I'm dealing with nested API responses from a Strapi application. I've set up a model using interfaces, but I'm having trouble accessing attributes from the product model when trying to access product data ...

The information retrieved from the API is not appearing as expected within the Angular 9 ABP framework

I am facing an issue with populating data in my select control, which is located in the header child component. The data comes from an API, but for some reason, it is not displaying correctly. https://i.stack.imgur.com/6JMzn.png. ngOnInit() { thi ...

How is it possible that my code is continuing to run when it is supposed to be

My API has a limitation of 50 requests per minute for any endpoint. In the code snippet below, I filter objects called orders based on their URLs and store the ones that return data in successfulResponses within my app.component.ts. Promise.all( orders.ma ...

Is there a way to adjust the StatusBar color or make it transparent on Android when working with NativeScript and Angular?

I am having trouble changing the StatusBar color in my NativeScript with Angular project. It currently appears as translucent black, darkening the background behind it. I want to either make it transparent or match the background color of the page. What I ...

Angular application hosted on Apache2 with SSL configured to communicate with a Spring Boot API running on port 8080

After developing a small application using Angular and an API with Spring Boot that includes an embedded Tomcat server, I decided to deploy them on a Raspberry Pi while configuring an SSL certificate with Let's Encrypt. The deployment process involve ...

Identifier for md-radio-group

In my Angular 4 Material application, I have a set of radio buttons grouped together: <md-radio-group fxLayout fxLayoutAlign="center center" fxLayoutGap="30px"> <md-radio-button value="1">Date</md-radio-button> <md-radio-butto ...