Streamlining Your Workflow: Using Angular to Edit Multiple Objects Simultaneously

I utilize a table to display data retrieved from my API. In my .ts component, I use the following method to access the service data:

getBloques() {
        this.configuracioncvService.getBloques()
          .subscribe(res => {
            let bloquesOrdenados = _.orderBy(res,['ordenCompleto'], ['asc'])
            this.configuracioncvService.bloques = bloquesOrdenados;
            console.log('BLOQUESRESTAPI', bloquesOrdenados)
          })
      }
    

The service method is defined as:

getBloques() {
        return this.http.get<Bloque[]>(this.URL_BLOQUES);
    }
    

To present the data in the HTML, I use the following code:

<table class="table" id="tabla">
        <thead>
             <tr class="d-flex">
                  <th class="col-3">Bloque</th>
                  <th class="col-3">Orden</th>
                  <th class="col-3">Guardar</th>
                  <th class="col-3">Ingresar a Bloque</th>
              </tr>
         </thead>
         <tbody>
              <tr class="d-flex" *ngFor="let bloque of configuracioncvService.bloques">
                   <td class="col-md-3">{{bloque.nombre}}</td>
                   <td class="col-md-3">
                        <mat-form-field>
                             <input type="number" matInput placeholder="Orden" [value]="bloque.ordenCompleto" [(ngModel)]="bloque.ordenCompleto">                                             
                        </mat-form-field>
                   </td>
                   <td class="col-md-3">
                        <button class="btn btn-secundary" (click)="editBloque(bloque)">
                             <i class="material-icons">save</i>
                        </button>
                   </td>
                   <td class="col-md-3">
                        <button mat-raised-button color="primary" [routerLink]="['/bloque-completo/', bloque.nombre]">
                             <i class="material-icons">east</i>
                        </button>
                   </td>
              </tr>
         </tbody>
    </table>
    

To achieve editing functionality for all objects with a single button, I have attempted using formArray and storing form values in an array. However, I am unsure how to loop through the array and edit.

https://stackblitz.com/edit/angular-formgroup-ngxxam?file=app%2Fapp.component.ts

Answer №1

Thanks to the assistance of a fellow user, I was able to accomplish this by utilizing ngModel and connecting each input with an object property. Here is how I implemented it in my html:

<ng-container *ngFor="let bloque of bloques">
  <input [(ngModel)]="bloque.nombre" disabled>
  <input [(ngModel)]="bloque.ordenCompleto">
</ng-container>
<br>
<button (click)="guardar()">
Save
</button>

In my .ts file:

export class AppComponent {

  bloques = [
    {
      id: 1,
      name: 'Articulos',
      completeOrder: 2,
      summarizedOrder: 2,
      customizableOrder: 2
    },
    {
      id: 4,
      name: 'Libros',
      completeOrder: 1,
      summarizedOrder: 1,
      customizableOrder: 1
    }
  ];

  originalBlocks = JSON.parse(JSON.stringify(this.blocks))

  save(){

    // iterate through each block

    this.blocks.forEach(block => {

      let originalBlock = this.originalBlocks.find(b => b.id == block.id)
      if(originalBlock.completeOrder == block.completeOrder) return


      // if the block was modified proceed to save it

      // this.configurationService.putBlock(block).subscribe(res =>{
      //   console.log('edited', res)
      // });
     })

  }
}

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

"Implementing a Node.js/Express backend paired with an Angular front-end within a unified Azure web application

Currently, I have set up a Node/Express configuration for my development environment that provides JSON data through the endpoint localhost:3000/data. In addition to this, there is an Angular 8 application within the same node directory for the frontend. ...

Return the previous value if the filter function returns false in RxJs

In an attempt to optimize performance and reduce unnecessary requests to the server, this code checks if values exist in the store before making additional requests. While the overall logic functions correctly, there is an issue where if the filter returns ...

What are the steps to display 10 items sequentially with the angular2-infinite-scroll package?

I'm currently working with the angular 2 infinite scroll module and I need to display 10 elements at a time. When the user scrolls down, the next 10 elements should be shown and the scrollbar should adjust accordingly. I've tried several methods ...

Issue with Angular 5 template: "AbstractControl type does not contain property 'length'"

While attempting to compile my Angular project using the command ng build --prod --output-path <my_destination_path>, I encountered a few errors like the following: ERROR in src/app/products/product-edit/product-edit.component.html(190,10): : Proper ...

In Certain Circumstances, Redirects Are Applicable

I have set up Private Routing in my project. With this configuration, if there is a token stored in the localStorage, users can access private routes. If not, they will be redirected to the /404 page: const token = localStorage.getItem('token'); ...

Avoid duplication of values in Angular4 when using *ngFor

Looking for assistance in updating an AngularJS project to Angular4. I have a JSON rest endpoint that returns a list of activities sorted by date and time. In AngularJS, I utilized ng-repeat to iterate through the data and ng-show to prevent duplicate entr ...

The Step-by-Step Guide to Deselecting an Angular Checkbox with a Button

I currently have a situation where I have three checkboxes labeled as parent 1, parent 2, and parent 3. Initially, when the page loads, parent 1 and parent 3 are checked by default, while parent 2 is unchecked. However, when I manually check parent 2 and c ...

How to transfer an object between sibling components in Angular 4

Being new to Angular 2+, I understand that I may not be approaching this the correct way. My issue involves two sibling components. When clicking on a "link" in one component, it redirects to another controller. My goal is to pass an object to the componen ...

The Postman successfully sends requests to the Express endpoint, however, the same endpoint fails to

Currently, I am developing an application that consists of both a front-end and a back-end. The front-end is built using Angular, while the back-end utilizes Node.js (Express). These two components communicate with each other through a Rest API. When send ...

Issue encountered: The .scss loader did not yield a string following the upgrade to cli version 7.3.6

After using ng update to upgrade my project, I encountered the following error when running ng build --prod: ERROR in The loader "...\ClientApp\src\app\nav-menu\nav-menu.component.scss" didn't return a string. Here is a li ...

What is the best approach to implement runtime configuration in Angular 15, ensuring that values can be provided in AppModule imports as well?

After two days of brainstorming, I am still struggling to figure out a way to read a config.json file located in my assets folder. I attempted to read this file during the bootstrapping process in main.ts so that I could use the values in my AppModule lik ...

Using Formik: When the initial value is changed, the props.value will be updated

After the initial props are updated, it is important to also update the values in the forms accordingly. export default withFormik({ mapPropsToValues: (props: Props) => { return ( { id: props.initialData.id, ...

Troubleshooting Angular directives and the complications of closures

I am facing a problem with this specific directive: @Directive({ selector: '[imgTest]', }) export class ImgTest implements AfterViewInit, OnDestroy { private originalImage: HTMLImageElement; private secondImage: HTMLDivElement; construc ...

Leveraging parameters within a sequence of object properties

Within the realm of Angular, I am dealing with interfaces that take on a structure similar to this (please note that this code is not my own): export interface Vehicles { id: number; cars: Car; trucks: Truck; } Export interface Car { make: ...

Confirm the existence of duplicates within an Angular reactive form

I am working with a reactive form that looks like this: https://stackblitz.com/edit/angular-form-array-example After clicking the "add credentials" button 3 times, I have 3 sets of elements for username and password. In the first row, I enter the usernam ...

Is Angular dockerization failing to run on the local port?

I am in the process of dockerizing my Angular app, and with the Dockerfile provided below, I have successfully built an image. However, I am unsure how to run this app locally on the port 4200 that I exposed. As a newcomer to Docker, any guidance on runnin ...

Encountering TS1204 error on version 1.5.0-beta with ES6 target, yet all functionalities are running smoothly

After successfully compiling everything from Typescript to ES6 to ES5, I encountered an error that has me stumped. The error message reads as follows: Error TS1204: Cannot compile external modules into amd or commonjs when targeting es6 or higher. Here i ...

The error message "Declaration file for module 'mime' not found" was issued when trying to pnpm firebase app

Currently, I am in the process of transitioning from yarn to pnpm within my turborepo monorepo setup. However, I have run into an issue while executing lint or build commands: ../../node_modules/.pnpm/@<a href="/cdn-cgi/l/email-protection" class="__cf_e ...

The error message "NullInjectorError: No provider for HTTP!" is generated by the ionic-native/http module

Currently working with ionic 3.2 and angular. To install the HTTP module (https://ionicframework.com/docs/native/http/), I used the following commands: ionic cordova plugin add cordova-plugin-advanced-http npm install --save @ionic-native/http In my scri ...

Ways to convert a string into a Date object without using moment.js

I am facing a challenge with 2 dates that are stored in the following format: "04.12.2019, 09:35" // Today "05.12.2019, 12:50" // Another date I need to compare these dates to determine if they have passed or are yet to come. My initial approach was to ...