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

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

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

Tailored validation for targeted field

How can I validate a partial form based on requirements? Built with Angular 7 and Clarity I have a form using the clrForm component that includes: Field 1: Name Field 2: URL Field 3: Date The form also has two buttons: Button 1: Verify Button 2: Su ...

Tips for successfully interacting with dynamic text areas using Protractor:

My current project involves e2e testing for an Angular 4 application with Protractor. Despite my efforts, I am struggling to locate a unique id, class, name or text identifier for a specific textarea within the application code. I need assistance in find ...

How do I rearrange the order of a collection in Firestore using a reference that I already have?

Is there a method to maintain a reference of the same collection while altering the ordering using firestore? TLDR: I am looking to achieve similar functionality as demonstrated in: , but since my data is sourced from firestore, I am struggling to find th ...

Updating an object within an array of objects in Angular

Imagine having a unique object array named itemArray with two items inside; { "totalItems": 2, "items": [ { "id": 1, "name": "dog" }, { "id": 2, "name": "cat" }, ] } If you receive an updated result for on ...

Experimenting with Date Object in Jest using Typescript and i18next

I have included a localization library and within my component, there is a date object defined like this: getDate = () => { const { t } = this.props; return new Date().toLocaleString(t('locale.name'), { weekday: "long", ...

Angular 2 Login Component Featuring Customizable Templates

Currently, I have set up an AppModule with a variety of components, including the AppComponent which serves as the template component with the router-outlet directive. I am looking to create an AuthModule that includes its own template AuthComponent situa ...

Combining PHP Arrays into a Single Array

Hello everyone, I have this specific output that I need to transform. Here is the initial output: string(47) "[{"value": "["Mouse","Cable Lock","Headset"]"}]" This is how I want it to look: " ...

jQuery AJAX returning an unexpected null value instead of JSON data

I'm currently working on a contact form that uses AJAX to submit data to a PHP file for processing. However, I'm facing some issues with retrieving the JSON object back into the AJAX command as it keeps returning null. Below is the code snippet t ...

TypeScript implementation of internationalization message extraction in Create React App

I am facing challenges in getting i18n messages extracted, as defined by react-intl's defineMessages, to function correctly in a TypeScript-based CRA. Here are the methods I've attempted: Initial Approach I tried following this guide to make i ...

Adding a custom role in Angular TypeScript in Microsoft AppInsights is a straightforward process that can provide valuable

I have an angular project where I am looking to incorporate AppInsight with custom telemetry (role). The project is built in Angular using TypeScript, and I successfully integrated appinsights by following this tutorial. However, when attempting to add cus ...

What is the preferred build tool to use with Deno?

It has come to my attention that deno no longer necessitates the use of package.json (compatible with npm/yarn) to detail its dependencies. However, when it comes to build/run scripts, is package.json still the recommended descriptor or are there alternat ...

Unable to locate the reference for 'bootstrap'

After trying to implement Bootstrap toast in an Angular Component, the following error message is displayed: "Cannot find name 'bootstrap'" Here is the HTML code similar to the Bootstrap documentation: <div class="toast" r ...

Validating Emoji Inputs in Angular

Is there a way to validate input for Emoji and display an error message if invalid? The form field in question is: 'name': new FormControl('', [Validators.required]), ...

Navigating through ionic2 with angularjs2 using for-each loops

I developed an application using IONIC-2 Beta version and I am interested in incorporating a for-each loop. Can anyone advise if it is possible to use for each in Angular-V2? Thank you. ...

How to retrieve values from multiple mat-sliders that are dynamically generated using ngFor loop

Creating multiple mat-sliders dynamically in Angular looks like this: <ng-container *ngFor="let parameter of parameterValues; let i = index;"> <mat-slider (input)="onInputChange($event)" min="1" max="{{ parameter.length }}" step="1" value="1" i ...

What is the best way to declare a classic C-Array directly in Objective-C?

Here is a code snippet that I'd like to optimize: NSUInteger indexArr[] = {1,2,3,4}; NSIndexSet *indexSet = [NSIndexPath indexPathWithIndexes:indexArr length:4]; I'm wondering if there's a way to declare the index array inline, similar to ...

A bash associative array designed to save every line beginning with the letter X

While working with a file containing lines of input, I am extracting the lines starting with X. The format of the lines is as follows: X B C D E X G H I J X L M N Y G Z B Y L In each line beginning with X, the second element serves as the key and the ...

Mastering the art of effectively capturing and incorporating error data

Is there a way to retain and add information to an Error object in typescript/javascript without losing the existing details? Currently, I handle it like this: try { // code that may throw an error } catch (e) { throw new Error(`Error while process ...

Extracting a single character from an NSarray using Objective-C

I am attempting to extract a character from an NSArray by randomly generating a number. Take a look at my code below: @interface ClassName : NSObject @property (nonatomic) char letter; -(id) init; -(char) changeLetter; @end Implementation File: #i ...

Parsing PHP array using JavaScript

$namesSelect = "SELECT username FROM users"; $names = mysql_query($namesSelect); $nameCheck = mysql_fetch_array($names) This code snippet retrieves all usernames from the users table and stores them in the $names array. I am now faced with the task of ...