Tips for updating a boolean value in a JSON file with a button in Angular and TypeScript

Can someone guide me on how to create a function in my table-viewer.component.ts file that can update the status from "false" to "true" in a JSON file when a user clicks the cancel button?

The JSON file has the following information.

db.json

"firstName": "Hamza",
"lastName": "Gallagher",
"carReg": "FG67 POI",
"parkingNumber": "00003",
"date": "2021-01-04",
"cancelled": false

etc ..

I am using Angular to display this data in a table, which looks like this: Image of table

Table-viewer.component.html

    <table class="table table-striped table-bordered table-hover">
  <thead>
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Car Registration</th>
    <th>Parking Number</th>
    <th>Date</th>
    <th>Status</th>
    <th></th>
  </tr>
  </thead>

  <tbody>
 <tr *ngFor="let booking of bookings">

   <td>{{booking.firstName}}</td>
   <td>{{booking.lastName}}</td>
   <td>{{booking.carReg}}</td>
   <td>{{booking.parkingNumber}}</td>
   <td>{{booking.date}}</td>
   <td>
     <div *ngIf="booking.cancelled" class="red">Cancelled</div>
     <div *ngIf="!booking.cancelled" class="green">Booked</div>
   </td>
   <td>
     <button class="btn btn-danger mr-2" (click)="cancelBooking()">Cancel</button>
   </td>
 </tr>

table-viewer.component.ts

export class TableViewerComponent implements OnInit {
  bookings: Booking[] = [];

  getBookings(): void {
    this.bookingService.getAll().subscribe((book: Booking[]) => {
      this.bookings = book;
    });
  }

  constructor(private bookingService: BookingService) {
  }

  ngOnInit(): void {
    this.getBookings();
  }

  cancelBooking(): void {
  //  Need assistance here
  }

}

booking.ts

export interface Booking {
  'firstName': string;
  'lastName': string;
  'carReg': string;
  'parkingNumber': string;
  'date': string;
  'cancelled': boolean;
}

Answer №1

It seems to me that the solution is quite straightforward:

    void cancelBooking(booking: Booking) {
        booking.cancelled = true;
}

All you need to do is call this method in the view.

Answer №2

Make sure to implement the following code snippet in your component.ts

cancelBooking(index): void {
  // Update booking status
  this.bookings[index].cancelled = true;
}

In the template file, replace the existing loop code with the code provided below:

<tr *ngFor="let booking of bookings; let i = index">

   <td>{{booking.firstName}}</td>
   <td>{{booking.lastName}}</td>
   <td>{{booking.carReg}}</td>
   <td>{{booking.parkingNumber}}</td>
   <td>{{booking.date}}</td>
   <td>
     <div *ngIf="booking.cancelled" class="red">Cancelled</div>
     <div *ngIf="!booking.cancelled" class="green">Booked</div>
   </td>
   <td>
     <button class="btn btn-danger mr-2" (click)="cancelBooking(i)">Cancel</button>
   </td>
 </tr>

Answer №3

Displaying Table Data in Angular Component

<table class="table table-striped table-bordered table-hover">
     ...
     <td>
       <button class="btn btn-danger mr-2" (click)="cancelBooking(booking: Booking)">Cancel</button>
     </td>
  </tr>

Handling Logic in Angular Component

export class TableViewerComponent implements OnInit {
   ...

  cancelBooking(booking): void {
     booking.cancelled = !booking.cancelled 
     // You can also set booking.cancelled to false or make other changes
   }
  }

Updating Data and Implementing Service Class

After making the changes in bookings array, it's important to create a service that can rewrite a JSON file based on these modifications.

Visit this link for more information

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

Dealing with 'TypeError X is Not a Function' Error in Angular (TypeScript): Occurrences in Certain Scenarios and Absence in Others

Recently, I came across an odd issue in Angular 14 where a type error kept popping up. Although I managed to refactor the code and find a workaround, I'm quite intrigued as to why this issue is happening so that I can prevent it from occurring again i ...

Ways to resolve the issue: "internal/modules/cjs/loader.js:638 throw err; ^"

I am encountering an error when trying to run my Vue.js project using npm on localhost:8080. Is there a solution to resolve this issue? This error specifically occurs when I attempt to install node_modules and package-lock.json in my Vue folder, which inc ...

Complete API Integration with Diverse Models for Android Development

Having trouble grasping some concepts about Rest API's. I successfully created 2 apps using JSON and POJO, where I had a large JSON file that allowed me to utilize Retrofit and move forward with the app. However, today I face a new challenge. I am tr ...

Updating JSON multiple times in the same row with different JSON paths

Looking to make multiple updates to a JSON data present in a row? Here's an example of the JSON structure: { "secondaries": [ { "secondaryId": 1, "primaries": [ { "primary": 1 ...

Acquire data through Reactive Form input

Struggling to populate my entity data in a reactive form. Data retrieval is successful, but unsure about the ideal method and timing for filling out the form with these values. Here's the structure of my form: import { Component, OnInit, Input } fr ...

The data type 'number' cannot be assigned to the data type 'undefined'. Error code: ts(2322)

I encountered an issue where it's giving me an error stating that type number cannot be assigned to type undefined on the last digit (1) in scale={[1.618, 1, 1]}. Can anyone help me figure out how to resolve this TypeScript error? "use client&quo ...

Obtain JSON information in a structured model layout using Angular 4

I have different categories in the backend and I would like to retrieve them in a model format. Here is how my model is structured: export class Category { name: string; id : string; } And this is how the data appears in the backend: { "name": "cars", ...

What could be the reason for the absence of Mock Service Worker in a React project that has Typescript enabled?

After attempting to integrate Mock Service Worker into my React project with Typescript support, I encountered errors when running the npm install msw --save-dev command. The terminal displayed the following messages: PS F:\Programming\React Prac ...

What is preventing type guarding in this particular instance for TypeScript?

Here is an example of some code I'm working on: type DataType = { name: string, age: number, } | { xy: [number, number] } function processInput(input: DataType) { if (input.name && input.age) { // Do something } e ...

Can you fill a spinner on an Android device by using a JSONArray?

Is it feasible to accomplish this task? Assuming I have a JSON array structured like below: { "locations": [ { "id": 1, "loc": "miami" }, { "id": 2, "loc": "manhattan" }, { "id": ...

Universal variable arguments

Is there a way to modify this function that accepts generic rest parameters to also accept an array parameter without using the spread operator? This would make chaining things much clearer: function fn<T>(...args: T[]): Something<T> { } let s ...

Adding items from the JSON data to a nested array at index i

In my project, I am working with two files: index.js and list.json. My goal is to extract an element from list.json and insert it into a nested array following the structure [hour][visits per hour]. The hour refers to the index of the hour; for example, ...

Function type guards in Typescript do not support type inference

When checking for null in alpha, I validate the result and use throw new Error if needed. However, even after doing so, the compiler still indicates a compilation error: const obj = { objMethod: function (): string | null { return 'always a str ...

problem encountered when running "ionic cordova build android --prod --release"

A chat application has been developed using Ionic2. Upon attempting to generate a production build with ionic cordova build android --prod --release, the following error is encountered. Error: ./node_modules/rxjs/observable/BoundCallbackObservable.js ...

Navigating the complexities of integrating Angular-based JS select/input values using CefSharp Offscreen on an external website: A comprehensive guide

I have encountered some challenges with setting input values on a third-party webpage that utilizes Angular for field validation. When attempting to set the value attribute using Chrome or CefSharp, the value does not update as expected. To work around th ...

Can [] be considered a valid type in Typescript language?

I've come across this function: function stringToArray(s: string|[]): [] { return typeof s === 'string' ? JSON.parse(s.replace(/'/g, '"')) : s; } This function is functioning as expected without any type warnings. Bu ...

Navigating the parent navController in Ionic 2: A step-by-step guide

I'm currently honing my skills in Ionic 2 by creating a basic app, but I've encountered an issue that has me stumped. The app features an ion-nav element for the login page, then transitions to a tabs navigator after successful login. The struct ...

Is it feasible to programmatically define the onClick action for an element within a ReactNode?

Let's discuss a function called addAlert that adds messages to an array for display as React Bootstrap alerts. While most alerts are simple text, there's one that comes with an "undo the last action" link. The challenge is that when this "undo" l ...

Utilize TypeScript to narrow down function parameters within a callback by evaluating other parameters

I'm currently working with traditional node callbacks. For example: myFunction('foo', (err: Error|null, data?: Buffer) =>{ if (err) { // typeof err is Error // typeof data is Buffer|undefined } else { // typeof err is nul ...

When attempting to run a Typescript Playwright test in Visual Studio Code's debug mode, it inexplicably fails to execute

I am fairly new to TypeScript and Playwright, but I have experience in coding. I believe I have a good understanding of what I am trying to achieve, but I am encountering a problem that I can't seem to figure out. I'm hoping someone can help me. ...