Adding new information to a list when a button is clicked: Combining Angular TypeScript with Laravel

Upon entering a reference ID in my system, it retrieves the corresponding record from the database. However, I am facing an issue where adding a new reference number overrides the existing record instead of appending it to the list.

https://i.sstatic.net/MVVDQ.jpg

To address this problem, below is the HTML and TypeScript code snippets:

<div *ngIf="show">
        <div class="form-group">
            <div class="col-sm-12">

                <label class="col-sm-12 cm">Details</label>

                <table class="table table-hover">
                    <tr>
                        <th>Reference ID</th>
                        <th>First Name</th>
                        <th>Surname</th>
                        <th>Reference </th>
                    </tr>

                        <td>{{Details.id}}</td> 
                        <td>{{Details.firstname}}</td>
                        <td>{{Details.lastname}}</td>
                        <td>{{Details.reference}}</td>

                </table>

            </div>
        </div>
    </div>
add() {
        const data = {
          reference: this.assistant.reference,
        }
        console.log(data);
        this.Service.add(data)
        .subscribe(
          req => {
            console.log("successful");
            this.show = true;
            this.Details.id = req['data']['member_record']['id'];
            this.Details.firstname = req['data']['member_record']['first_name'];
            this.Details.lastname = req['data']['member_record']['last_name'];
            this.Details.reference = req['data']['member_record']['reference'];
          },
          error => {
            console.log(error);
          }

        );
      }

If anyone can assist with dynamically appending records to the list on button click, it would be greatly appreciated. Additionally, tips on how to remove these UI records without affecting the database entries would be helpful as well.

Answer №1

Here is the solution provided for you,

For your .html file:

<table>
    <th>
      <td>ID Number</td>
      <td>First Name</td>
      <td>Last Name</td>
      <td>Reference Number</td>
    </th>
    <tr *ngFor="let detail of details">
      <td>{{detail.id}}</td>
      <td>{{detail.firstName}}</td>
      <td>{{detail.surName}}</td>
      <td>{{detail.reference}}</td>
    </tr>
</table>

Information related to detail.model.ts can be found here:

export class Detail {
  id : number;
  firstName : string;
  surName : string;
  reference : string;
}

In your TypeScript file (.ts):

details : Detail[] = [];

If you have an add button, ensure that the function call add() works properly and is implemented as below:

add(){
   detail = getRecordFromDb(); // Retrieve the generated record from the table.
   this.details.push(detail); // Add the retrieved record into the details array.
}

Answer №2

If you need to add items to an existing list, there is a handy workaround that can help.

this.details=([... this.details,...detail])

In this scenario, 'details' represents the list where we can continuously add items, while 'detail' is the new model that can be obtained each time. As a result, the 'details' list will keep growing with new data without replacing any existing 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

Setting up a route configuration to automatically redirect users to a parent and child route upon app launch

After searching through the Udemy tutorial and Angular2 documentation, I still can't figure out why my redirect isn't working. I want my app to directly navigate to the /whatsup/today component upon loading, but despite successfully redirecting t ...

Formatting numbers within the ngModel directive

How can I properly format a number using ngModel? When I attempted to do it like this <input type="number" [(ngModel)]="name.name.price | number:'1.2-3'">, it resulted in an error. What steps should I take to fix this is ...

Atom-typescript does not always successfully compile all typescript files to JavaScript

Currently, I am in the process of learning how to implement routing in Angular2 by following a tutorial. The tutorial involves creating partial pages using .ts files along with companion .js files for each page. While my Atom editor, equipped with atom-typ ...

Having trouble retrieving the value of a variable declared in a different function within an Angular project

I am encountering an issue when trying to retrieve the value of the existResults variable within a function that is called before the one where the variable is declared. The value returned is undefined. public existResults: any; ngOnInit(): void { ...

What could be the reason for my button not activating my JavaScript function?

I am encountering an issue with my form-validation sample. When I click the submit button, it should display an alert message but it is not working as expected. Here is a link to my sample: sample link I would greatly appreciate any assistance in res ...

Instructions for activating the "Navigate to Declaration" feature in TypeScript for JSON files using i18next

Currently, I am actively engaged in a project that involves the use of i18next with react and typescript. In this project, translation keys are defined within .json files. However, a notable drawback of transitioning to json for the translation files is l ...

Automating a login prompt with dual inputs using WebdriverIO: A step-by-step guide

I'm having trouble automating the login prompt as shown in the attached image. I've attempted to fill in both fields using WebdriverIO but so far have been unsuccessful. I explored using alert methods like browser.sendAlertText(), but none of the ...

An unusual occurrence of events may occur when serverTimestamp fields are added to a Firestore collection alongside new elements

I've developed a web application where users can share messages on a specific topic. I'm utilizing Firebase as the backend with data stored in Firestore. Each message object contains an ID, content, creation timestamp, and last updated timestamp. ...

How to conceal duplicate items in Angular2

In my Angular 2/4 application, I am fetching data from a web API (JSON) and displaying it in a table. In AngularJS, I use the following code: <tbody ng-repeat="data in ProductData | filter:search | isAreaGroup:selectedArea"> <tr style="backgro ...

What are the best practices for transpiling code using Parcel-bundler?

Currently, I am attempting to transpile both .ts (TYPESCRIPT) and .scss (SASS) files. However, I am encountering two main issues: 1) Instead of generating my file in the designated dist directory, it is creating a dist directory within the build folder. ...

Using regex to replace problems with line breaks with BR tags

I have a block of text that I need to modify by replacing BR tags with \n in order to create new lines. D:\HP\ConfigurationServer_3464\log\nvdmr***.log ~ File not found<br>D:\HP\DCSSchedulerAgent_3478\logs&bso ...

Angular 4 navigation troubles

I'm currently working on a project using Angular 4 and I need to implement navigation to another page upon clicking any component. The specific component I want to use for this navigation is located in the dashboard1 page. This component will navigat ...

Checking the value of a row in an Angular Material table when a checkbox is

I am working with an Angular Material table that has rows with checkboxes. To view the example of this, please visit Material Table. I would like to perform a manipulation on other fields based on the checkbox selection status of a row. ...

There was an error encountered trying to access the options (URL) with a 405 method not allowed status. Additionally, the request to load the (URL) failed with a response indicating an

I attempted to retrieve data from an API using httpClient in Angular 5, but encountered errors. Below are the issues I faced: 1) ERROR: when trying to access http://localhost:8080/api/getdata, I received a 405 error (method not allowed). 2) ERROR: failed t ...

Troubleshooting the issue of Angular2's http withCredentials not functioning as expected

Utilizing Angular2's HTTP module, I am sending HTTP requests. Once a user logs in, the backend server creates a cookie session which is then used by the frontend to send subsequent requests. The Angular code snippet is outlined below: get(url: string ...

Troubleshooting Paths with Angular's NgFor Directive

Within my Angular project, I have implemented a basic ngFor loop to display logo images. Here is a snippet of the code: <div *ngFor="let item of list" class="logo-wrapper"> <div class="customer-logo"> & ...

TS & Angular: Unlocking the Power of Conditional Interfaces

My user component includes a variable called user, which can be either an Employee or a Student. In my HTML, I have an element {{ user.coure ?? user.department }} I'm encountering an issue in my HTML because some properties in the Employee interface ...

The version of the replication configuration schema does not support the use of ReplicationTime

I am currently working on setting up S3 Replication using the AWS CDK. I have referenced https://github.com/rogerchi/cdk-s3-bucketreplication/blob/main/src/index.ts as a starting point, and while it does create a replication rule, I am facing some issues c ...

Using type as an argument in a hook in a similar fashion to how it is

My custom hook utilizes Zustand and is capable of storing various data types. However, I am looking to specify the type of data that will be stored similar to how it is done with the useState hook. import { Profile } from "@/types"; import { crea ...

Angular 4 Form remains valid even when an incorrect value is entered

Within my Angular 4 project, I encounter the issue of controlling input fields in multiple forms. Specifically, I need a mechanism to disable the save button if the input value is incorrect. For example, when I require an input field to only accept positi ...