When the add button in Angular is clicked, I would like the summary section, item name, and price to be updated accordingly

How can I dynamically update the summary section with the item name and price every time I click on add without removing the previous entries?

booking.component.html

<table class="container table table-striped table-hover">
    <thead>
      <tr>
        <th scope="col">Activity</th>
        <th scope="col">Name</th>
        <th scope="col">1 hour</th>
        <th scope="col">30 min.</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of bookAdd">
        <td>img</td>
        <td>{{ item.name }}</td>
        <td *ngFor="let pointer of item.price; index as i">
          {{ pointer }}
          <button
            type="button"
            class="btn btn-dark btn-sm"
            (click)="addTotalPrice(pointer); addName(item.name); addPrice(pointer)"
          >
            Add
          </button>
        </td>
      </tr>
    </tbody>
  </table>
  <div class="container">
    <div class="row">
      <div class="col-3 card">
        <h3 class="center">summary</h3>
        <p>
         {{name}} {{price}} 
        </p>
        <h4>total {{ total }}</h4>
      </div>
    </div>
  </div>

booking.component.ts

   bookAdd: Booking[] = [];
   total = 0;
    name:  any;
    price: any;
 
  ngOnInit(): void {

    this.booking.getBooking().subscribe((data) => {
      this.bookAdd = data;
      console.log(this.bookAdd);
    });


  }

  addTotalPrice(price: number ,) {
    this.total += price;

  }
  addName(name:any ) {

    this.name = name;
  }
  addPrice (price: number) {
    this.price = price;
  }

https://drive.google.com/file/d/1lIjWCVvz-iSm9MlHxWXLOA2c_Hka6SrB/view?usp=sharing

Answer №1

I made some improvements to the code.

  1. Avoid adding multiple listeners for methods, instead add methods to a listener
    (click)="method(); otherMethod()"
  2. Remember to unsubscribe using takeUntil(this.unsubscribe$)
  3. Don't forget to implement all members required by implements OnInit

Here is the HTML snippet:

<table class="container table table-striped table-hover">
  <thead>
    <tr>
      <th scope="col">Activity</th>
      <th scope="col">Name</th>
      <th scope="col">1 hour</th>
      <th scope="col">30 min.</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let book of books">
      <td>img</td>
      <td>{{ book.name }}</td>
      <td>
        <button
          *ngIf="!addedBooks.includes(book)"
          type="button"
          class="btn btn-dark btn-sm"
          (click)="addBook(book)"
        >
          Add
        </button>
        <span *ngIf="addedBooks.includes(book)">(added!)</span>
      </td>
    </tr>
  </tbody>
</table>
<div class="container">
  <div class="row">
    <div class="col-3 card">
      <h3 class="center">summary</h3>
      <p>
        <ng-container *ngFor="let addedBook of addedBooks">
          {{ addedBook.name }} {{ addedBook.price }}
        </ng-container>
      </p>
      <h4>total {{ totalPrice }}</h4>
    </div>
  </div>
</div>
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit, OnDestroy {
  books: Book[] = [];
  addedBooks: Book[] = [];
  totalPrice: number;
  unsubscribe$: Subject<void> = new Subject();

  mockData = [
    { name: 'Lord of the Rings', price: 50 },
    { name: 'Dune', price: 100 },
  ];
  ngOnInit(): void {
    of(this.mockData)
      .pipe(takeUntil(this.unsubscribe$))
      .subscribe((data) => {
        this.books = data;
        console.log(this.books);
      });
  }

  addBook(book: Book) {
    this.addedBooks.push(book);

    let sum = 0;
    this.addedBooks.forEach((book) => {
      sum += book.price;
    });
    this.totalPrice = sum;
  }

  ngOnDestroy() {
    this.unsubscribe$.next();
  }
}

export interface Book {
  name: string;
  price: number;
}

See the working example here: https://stackblitz.com/edit/angular-ivy-irn9to?file=src%2Fapp%2Fapp.component.ts

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

Observables and the categorization of response data

Understanding Observables can be a bit tricky for me at times, leading to some confusion. Let's say we are subscribing to getData in order to retrieve JSON data asynchronously: this.getData(id) .subscribe(res => { console.log(data.ite ...

What is the process of extending a class in TypeScript?

I have a few services that contain the same code: constructor (private http: Http) { //use XHR object let _build = (<any> http)._backend._browserXHR.build; (<any> http)._backend._browserXHR.build = () => { let _xhr = _ ...

What's the issue with conducting a unit test on a component that has dependencies with further dependencies?

I am experiencing an annoying error that seems to be my mistake and I cannot figure out how to resolve it. The issue lies within a simple component which serves as a top-bar element in my web application. This component has only one dependency, the UserSe ...

Creating a Type that limits its keys to those from another Type, with the ability to assign new values to those keys. Attempting to introduce new keys should result in an

type Numbers = { a: number; b: number; f: number; }; type ValidateKeysWithDifferentTypes = SomeThingKeyOf<Numbers> & { a: string; b: Date; c: null; // Error occurs because 'c' is not found in Numbers type? // Error due ...

Something went wrong: Unable to access the properties of an undefined variable named 'gametitle'

I am able to see the variables on the html-page, but I encountered an error specifically with the value of the gametitle ERROR TypeError: Cannot read properties of undefined (reading 'gametitle') Below is the content of the ts-file: import { ...

Troubleshooting TypeScript Node.js Compilation Issue

In my quest to establish a debugging environment for a project from 2019, I included the following script in my package.json: "dev:debug": "tsc-watch --onFirstSuccess \"node --inspect -r ts-node/register src/app.ts\"", Executing this script pro ...

The type 'string | undefined' cannot be assigned to type 'string'

I am facing a challenge in comparing two arrays, where one array is sourced from a third-party AWS service and its existence cannot be guaranteed. Despite my efforts to handle potential errors by incorporating return statements in my function calls, I con ...

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 ...

In a Custom Next.js App component, React props do not cascade down

I recently developed a custom next.js App component as a class with the purpose of overriding the componentDidMount function to initialize Google Analytics. class MyApp extends App { async componentDidMount(): Promise<void> { await initia ...

What are the steps to incorporate a type-safe builder using phantom types in TypeScript?

In order to ensure that the .build() method can only be called once all mandatory parameters have been filled, it is important to implement validation within the constructor. ...

The .map() operator requires a declaration or statement to be specified - TS1128 error

I've tried various solutions from different sources but none seem to be resolving the issue I'm facing. The problem is: when trying to run my app, I encounter the following error: 10% building modules 0/1 modules 1 active …\src\a ...

Creating an array object in TypeScript is a straightforward process

Working on an Angular 4 project, I am attempting to declare an attribute in a component class that is an object containing multiple arrays, structured like this: history: { Movies: Array<Media>, Images: Array<Media>, Music: Array<Medi ...

In my array, I have numerous objects that need to be inserted into a PostgreSQL database using a single query executed from a Node.js environment

After receiving the data from the frontend, all the information is stored in req.body. The next step involves mapping the data and attempting to insert it, however, an error is being encountered. router.post('/addItems', (req, res) => { ...

Retrieving Child Route Parameters in Angular 7

Fetching the parameter 'id' only from the corresponding page component seems to be a challenge. The params id cannot be accessed from other individual components such as the header component. //The code snippet below works only in the correspond ...

Achieve the capability to upload multiple files in Next.js using the upload.io integration feature

I'm currently using upload.io for uploads and replicate.com for an AI model on a specific app. I am able to upload one picture, but unfortunately, I am encountering issues when trying to upload multiple pictures. Can anyone identify the problem here? ...

The disappearance of UI elements in Angular 13 and Bootstrap 5 when new routes are introduced

After spending a considerable amount of time on website development, I have hit a roadblock with the navigation. Whenever I set up a route, the entire user interface disappears and refuses to load. I have searched extensively but found no solution to this ...

Utilize Angular 5 to implement URL routing by clicking a button, while also preserving the querystring parameters within the URL

I have a link that looks like this http://localhost:4200/cr/hearings?UserID=61644&AppID=15&AppGroupID=118&SelectedCaseID=13585783&SelectedRoleID=0 The router module is set up to display content based on the above URL structure { path: & ...

I am unsure why it is displaying these errors

I created an auto-fill form that populates data based on ng-select information automatically. However, I am encountering an issue when attempting to delete selected data as it is throwing a Cannot read property 'pincode' of null error. Any help i ...

Testing with Sinon and TypeScript returns an empty object

Trying to incorporate sinon into a TypeScript project and make use of its sandboxing capabilities. I have followed the suggested approach to wrap my tests, but encountered an issue when trying to call this.stub(/<em>stuff</em>/) according to th ...

How to authenticate users using JWT in Angular and retrieve user data?

I've developed an Angular project with JWT login functionality to communicate with the backend. Once I receive a token, my goal is to retrieve user information from the backend. Below is the code snippet from my authentication service: login(username: ...