For editing values that have been dynamically inserted

In my JSON data, there is a variable named address that contains multiple objects (i.e., multiple addresses). I am displaying these multiple addresses as shown in the following image:

https://i.sstatic.net/1AG34.png

  • When clicking on a specific address (e.g., addressType: Business), the values of that address (such as postalCode and City) are displayed in the input fields below. After editing the address, upon hitting the add button, the edited address is saved, but the input fields should be cleared, as shown in this image:

https://i.sstatic.net/NXCH0.png

However, I am currently unable to clear the input fields without refreshing the page in order to add a new address.

  • By clicking on delete, I should be able to delete that particular address.

DEMO

Answer №1

If you want to ensure the form is cleared after updating the data, don't forget to utilize the reset method.

saveAddress(index, form: FormGroup) {
    if (this.mode === 'add') {
      this.contacts[index].addresses.push({ ...this.newAttribute });
      form.reset();
    } else if (this.mode === 'update') {
      Object.assign(this.selectedAddr, this.newAttribute);
      form.reset();  // The form is reset at this point
    }
}

For deletion purposes -

deleteRecord(i, j){
    this.contacts[i].addresses.splice(j, 1);
}

<div class="main" *ngFor="let contact of contacts;let i = index">

<form [formGroup]="addForm" #myForm>

  <p>Name: {{contact.name}}</p>
  <br>
<!-- Address section -->
      <div  class="address-sec">
        <p id="addr">Addresses</p>
        <br>
        <table style="width:100%" *ngFor="let addr of contact.addresses; let j = index">
            <tr>
                ....
                <td>
                    <div class="field-data" (click)='deleteRecord(i,j)'>
                    <b>Delete</b>
                   </div>
                </td>
            </tr>
          </table>
        <hr>
        <br>
      </div>

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

Are we on the correct path for breaking down code using react JS?

As I work on creating reusable table components, each column comes with its own set of functionalities, which results in dealing with numerous components. To streamline the process, I have been separating every component piece into individual files and ex ...

Contact the help desk and receive information that is currently unknown

There are a few issues that I'm struggling to resolve. I am utilizing SwaggerService to fetch data, but the response is coming back as undefined. import {SwaggerService} from '../../services/swagger.service'; export class TestComponent im ...

How can the component prefix be replaced or updated in Angular 8/9?

Is there a way to efficiently replace or modify the outdated component prefix all at once? OR How can I create a dynamic prefix system that automatically updates all component prefixes whenever changes are needed? ...

Validating PrimeNG Tables

I have a PrimeNG Table with only one editable column called "Value". Here is the StackBlitz demo for reference. https://stackblitz.com/edit/datatablevalidation In the "Value" column, I need to implement validation based on the value in the corresponding ...

What causes the 401 error to be triggered when utilizing an interceptor?

Working on an Angular 9 Single Page Application that interacts with a JWT-enabled API. Encountering a 401 error when trying to incorporate the provided interceptor. Any insights on what might be causing this issue? It is worth noting that the application ...

Fixing permission issues during the installation of Angular Client on MacOS: A comprehensive guide

As a beginner coder diving into Angular and Node through an Udemy tutorial, I've encountered some issues. While I have successfully installed Node.js version 16.15.1, my attempts to install the angular client have consistently failed (see screenshot a ...

Troubleshooting npm installation issues with Angular 2 Quickstart guide (URL: https://angular.io/docs/js/latest/quickstart.html)

I am currently facing issues when trying to set up Angular 2 on my Ubuntu 15.10 system. Despite multiple attempts, the installation fails and I receive error messages. Even after attempting to install Angular 2 using the npm package command sudo npm insta ...

Converting keyValue format into an Array in Angular using Typescript

Is there a way to change the key-value pair format into an array? I have received data in the following format and need to convert it into an array within a .TS file. countryNew: { IN: 159201 BD: 82500 PK: 14237 UA: 486 RU: 9825 } This needs to be transf ...

A function injected into a constructor of a class causes an undefined error

As I delve into learning about utilizing typescript for constructing API's, I have encountered a couple of challenges at the moment. Initially, I have developed a fairly straightforward PostController Class that has the ability to accept a use-case wh ...

When running the ng test command, the error "TypeError: The 'compilation' argument must be an instance of Compilation" is generated, but the ng build command functions correctly

When attempting to execute unit tests using 'ng test libraryprojectname', I encounter the following error. Interestingly, ng build functions properly without any issues. The project in question is a workspace that includes an Angular library. Any ...

Exploring the Power of Map with Angular 6 HttpClient

My goal is to enhance my learning by fetching data from a mock JSON API and adding "hey" to all titles before returning an Observable. Currently, I am able to display the data without any issues if I don't use the Map operator. However, when I do use ...

Issue with Webpack throwing 'window undefined' persists despite using the 'use client' configuration in React/Next.js

I've been using Typescript 5, React 18, and Next.js 14 as my tech stack, and I keep encountering similar errors with various libraries. One of the errors I often face is ReferenceError: window is not defined. This error originates from a third-party ...

An error has occurred: Type 'x' is not compatible with type 'x' (during Vercel deployment)

I encountered an issue during Vercel deployment which displays the following error message: - Type error: Type ' ({ params }: DashboardPageProps) = Promise' is not compatible with type 'FC<.DashboardPageProps>' Type 'Promise ...

Using the spread operator in Typescript with an object that contains methods

Within my Angular project, I am faced with an object that includes a type and status field where the status can change depending on the type. While some might argue that this is not the best design practice, it is how things are currently structured in my ...

Is it true that one must have 280 different dependencies in order to use angular2?

Currently, I am following the ng2 getting started tutorial outlined here. It mainly involves working with a default package.json and running npm install. The package.json specifically lists two dev dependencies, while the rest are essential first or secon ...

Issues encountered when utilizing a computed property in Typescript to organize an array

Attempting to implement Vue in a typescript single page application, I encountered a challenge where arrays needed to be displayed on screen in sorted lists. Despite the seemingly simple nature of the problem, none of the examples I came across seemed to w ...

Enhancing React Flow to provide updated selection and hover functionality

After diving into react flow, I found it to be quite user-friendly. However, I've hit a roadblock while attempting to update the styles of a selected node. My current workaround involves using useState to modify the style object for a specific Id. Is ...

Is it possible to secure an API endpoint from unauthorized access by external authenticated users not originating from the requesting application?

Currently, I am developing an Angular application where users can log in, track their progress, and earn levels/experience points. The app uses a Node.js/Express API for backend functionality, and I need to implement a way for the app to award experience ...

Can you use the useCallback function within a nested callback function?

within component A: const retrieveOnClick = useCallback( (rec: GenericRec): (() => void) => () => { setSelectedRecord(rec); }, [], ); inside component B which is a child of A: const displayRecord = useCallback( (row: Row& ...

Solving the 'ExpressionChangedAfterItHasBeenCheckedError' in Angular 8

In my current project, I have developed a component that is responsible for uploading files to a database. As part of the user interface, I added an overlay that displays information about the number of files selected and the number of files successfully u ...