Sending an array of data using Angular in a web service

Here is my model object from model.ts

 name_id: string[];  public generateUrlencodedParameters(token: string, id?: number): string {

        let urlSearchParams = new URLSearchParams();
        urlSearchParams.append('name_id', this.name_id.toString());

Now moving to component.ts

this.MyForm = new FormGroup({
      'name_id': this.fb.array([])
    });

  onAddItem() {
    (<FormArray>this.MyForm.controls['name_id']).push(new FormControl('', Validators.required));   }

Lastly, in the component.html file

 <div class="row">
    <div formArrayName="name_id">
      <div class="form-group" *ngFor="let name of MyForm.get('name_id').controls; let name_id = index">
        <br>
        <input class="form-control" formControlName="{{name_id}}">
      </div>
    </div>
    <div class="input-field col s4">
      <button type="button" class="btn btn-primary" (click)="onAddItem ()">+</button>
    </div>   </div>

I am facing an issue where when I post it to the webservice, it gets formatted as

name_id=FA163EBBBC1D%2C11E7FF6%2C11E7FF6FC1D
, separating the array with %2C. Can anyone help me with this problem?

Answer №1

Developing a well-structured form

  <div class="col">
    <form [formGroup]="MyForm" (ngSubmit)="onSubmit()">
    <div formArrayName="name_id" >
      <div class="form-group" *ngFor="let name of MyForm.get('name_id').controls; let name_id = index">
        <br>
        <input class="form-control" formControlName="{{name_id}}">
      </div>
    </div>
    <div class="input-field col s4">
      <button type="button" class="btn btn-primary" (click)="onAddItem ()">+</button>
    </div>
      <button class="btn primary-btn" type="submit">Submit </button>
    </form>
  </div>

Utilize console log for troubleshooting within your component We can access a reactive FormArray using this syntax

(<FormArray>this.MyForm.controls['name_id'])).at( <index>)

Alternatively, you can simplify it by retrieving its control and invoking methods of that controller

  onSubmit() {
    let nameIdCtrl = <FormArray>this.MyForm.controls['name_id']);
    console.log(nameIdCtrl.at(0).value);
  }

Ensure that the first input is displayed correctly when debugging

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

Exploring the process of iterating over asynchronous data in Angular

There is an angular component in my project that fetches data from the server, processes it, and then assigns it to a variable: class Component { data = []; ngOnInit() { this.store.select(data).pipe( map(data => { this.data = this.transf ...

Comparison between modules and standalone components

It has come to my attention that there is a growing trend in Angular 17 to move away from using modules, opting instead for standalone components. This approach makes Angular more similar to Vuejs or React, where the concept of modules is not as prominent. ...

Lookup users either by their email or their unique primary key in the form of a UUID

Currently, I am utilizing typeorm along with typescript and the postgresql driver Within my controller, below is a snippet of code: const userRepository = getCustomRepository(UserRepositories); const query = { by_email: {where: {email: user_receiver} }, b ...

Circular structure error occurred when attempting to convert an object to JSON, starting at an object constructed with the constructor 'Object'

I am facing an issue where I need to update a Medico from the collection, and I have successfully destructured the data of the Medico's name and email. Additionally, I have obtained the ID of the assigned hospital. However, I am having trouble sendin ...

How to Incorporate and Utilize Untyped Leaflet JavaScript Plugin with TypeScript 2 in Angular 2 Application

I have successfully integrated the LeafletJS library into my Angular 2 application by including the type definition (leaflet.d.ts) and the leaflet node module. However, I am facing an issue while trying to import a plugin for the Leaflet library called "le ...

Submitting a form with Multer when the user chooses to upload a file or not

I have integrated multer into my express app for handling form submissions. The issue I am facing is with the optional image upload feature in the form. Users have the choice to add a photo if they want, but they should also be able to submit the form wi ...

How can I configure nest.js to route all requests to index.html in an Angular application?

I am developing an Angular and NestJS application, and my goal is to serve the index.html file for all routes. Main.ts File: async function bootstrap() { const app = await NestFactory.create(AppModule); app.useStaticAssets(join(__dirname, '..&ap ...

What is the best way to obtain user-inputted data from a dynamic input table with dynamically added rows?

I am struggling to fetch the user-entered data from a dynamic inputs table. Each time a new row is added dynamically to the table, I have to create a new array in the component.ts file to retrieve the data using Two-way data binding. Below is the HTML cod ...

Using React Material UI to create multiple collapse components

Currently, I am facing an issue where all the collapses in my list are linked to one state for "open." This means that if I open one list, all the other lists also open. I am looking for a way to keep the collapses separate from each other without needing ...

Problem with Angular 5: Data Binding Issue未知EncodingException

Struggling to understand... I want to make a GET request to my service to retrieve the specific hardware associated with the barcode I scanned - this part is working correctly. The hardware information is returned as an object that looks like this -> How ...

Transfer data from distinct arrays to separate variables

I have 2 arrays structured like this: let dataA = [{"id": "a1", "name": "Alpha"}, {"id": "a2", "name": "Beta"}, {"id": "a3", "name": "Gamma&quo ...

I'm having trouble getting any data to emit when I subscribe to a state service subject that stores a hovered element. What could I be missing?

I am currently working on a project that involves a calendar, a hover directive, and a stateful service for communication. Here's a simplified representation of my work so far: https://stackblitz.com/edit/stackblitz-starters-kvzyvy?file=src%2Fmain.ts ...

PHP Arrays - the everlasting reference

Is it possible to create a PHP array that is always treated by reference without the requirement of using the & operator? For example: $arr1 = ref_array('x', 'y', 'z'); $arr2 = $arr1; $arr2[] = 'w'; should res ...

I am continuously receiving the message "Alert: It is important for every child in a list to possess a distinct "key" prop." while working with the <option> list

Having trouble generating unique keys for my elements. I've tried different values and even Math.random() but still can't seem to get it right. I know the key should also be added to the outer element, but in this case, I'm not sure which on ...

Issue occurs where the system is unable to recognize a defined variable, despite it being clearly defined

I keep encountering an error message stating that my variable is not defined, even though I have clearly defined it just a few lines above where the error occurs. The reason behind this error is baffling to me, as I cannot identify any potential triggers ...

Enhancing the Value of BehaviorSubject with Object Assign in Angular using Typescript and RxJs

I have a user object stored as a BehaviorSubject which is being observed. I need help figuring out how to detect if a specific value within my user object has changed. I've noticed that my current implementation doesn't seem to work correctly, a ...

Best method to incorporate JSON array from WebService into a Dataframe

I have a column titled 'code' that I need to send to a web service in order to update two specific fields (dfMRD1['Cache_Ticker'] and dfMRD1['Cache_Product']) with data retrieved from the JSON response, specifically the values ...

getItemForm does not make a second promise call

I have a scenario where my function calls the api.send service twice, however when I run a test expecting it to resolve both promises, only res1 is returned and not res2. How can I ensure that both promises are resolved successfully? Here is my function: ...

Effectively managing intricate and nested JSON objects within Angular's API service

As I work on creating an API service for a carwash, I am faced with the challenge of handling a large and complex json object (referred to as the Carwash object). Each property within this object is essentially another object that consists of a mix of simp ...

The ng-bootstrap ngb-accordion component in Angular2 is not visible on the screen

Even though my HTML content loads successfully (displaying "HI", "title1", and "objName11" within span tags), the ngb-accordion component is not rendering on the view. I'm struggling to identify what I might have missed. There are no compilation or b ...