Pass a String Array to FormArray: A Complete Guide

This is my Custom Form Group:

this.productGroup = this.fb.group({
  name: ['', Validators.compose([Validators.required, Validators.maxLength(80)])],
  variants: this.fb.array([
    this.fb.group({
      type: '',
      options: this.fb.array([])
    })
  ])
});

I am trying to figure out how to pass a string array to options. For example, like this: [ 'string1', 'string2' ]. I have been working on it dynamically and you can see my progress on this stackblitz link. However, I am still unsure about how to fill the array. My goal is to pass a generic string array directly to options.

An example of the variants array structure:

variants: [ 
   { type: 'Color', options: ['Red', 'Blue'] },
   { type: 'Size', options: ['Small', 'Medium', 'Big'] }
]

Here is the HTML code snippet:

<form [formGroup]="productGroup">
  <input formControlName="name">
  <div formArrayName="variants" *ngFor="let item of productGroup.controls['variants'].controls; let i = index;">
    <div [formGroupName]="i">
      <mat-form-field>
        <input type="text" placeholder="Variable Type" aria-label="Number" matInput formControlName="type" [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete">
          <mat-option *ngFor="let type of types" [value]="type">
            {{type}}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>
      <mat-form-field>
        <mat-chip-list #chipList>
          <mat-chip *ngFor="let opt of typesOptionsArray[i]" [selectable]="true"
                    [removable]="true" (removed)="removeOpt(opt, i)">
            {{opt}}
            <mat-icon matChipRemove>cancel</mat-icon>
          </mat-chip>
          <input placeholder="Type Options"
                  [matChipInputFor]="chipList"
                  [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
                  [matChipInputAddOnBlur]="true"
                  (matChipInputTokenEnd)="addOpt($event, i)">
        </mat-chip-list>
      </mat-form-field>
    </div>
    <div class="row">
      <a href="javascript:" (click)="addItem()"> Add Variant </a>
      <a href="javascript:" (click)="removeItem(i)" *ngIf="i > 0"> Remove Variant </a>
    </div>
  </div>
</form>

Answer №1

I have developed a demo application on StackBlitz to showcase adding array values in the options array.

Instead of FormArray for the options field, I recommend using FormControl. The code for creating FormGroup has been modified accordingly.

Below is the updated formgroup code:

 this.productGroup = this.fb.group({
  name: ['', Validators.compose([Validators.required, Validators.maxLength(80)])],
  variants: this.fb.array([
    this.fb.group({
      type: '',
      options: ''
    })
  ])
});

In the component, I have introduced two methods 'addOption' and 'removeOption' to handle option additions by pushing strings into the options array at that time.

Here is the snippet of code:

let variants = <FormArray>this.productGroup.controls.variants;
let variantFormGroup = <FormGroup>variants.controls[0];
let optionValue = variantFormGroup.controls.options.value;
if(!optionValue)
    optionValue = [];
optionValue.push(`chip${this.currentIndex}`); // push your actual string value
variantFormGroup.controls.options.setValue(optionValue);

this.currentIndex++; //Just for adding new names, disregard if not needed

Also, here is the code snippet for removing a string value from the options array:

 let optionValue = this.productGroup.value.variants[0].options;
    if(optionValue.length > 0){
      //let indexOf = optionValue.indexOf(removeValue); Determine index number for the value you wish to remove.
      optionValue.splice(0,1);
      let variants = <FormArray>this.productGroup.controls.variants;
      let variantFormGroup = <FormGroup>variants.controls[0];
      variantFormGroup.controls.options.setValue(optionValue);

    }    

Upon adding some values to the options array, below is the resulting JSON output:

{ "name": "", "variants": [ { "type": "", "options": [ "chip4", "chip5", "chip6", "chip7", "chip8" ] } ] }

If you have any queries, feel free to ask.

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

encountering issues with resolving dependency tree while attempting to create an Ionic app

Hey, I've been trying to build an ionic app but keep encountering this error that I'm unable to resolve: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! Found: <a href="/cdn-cgi/l/email-protection" ...

Tips for managing a multi-page website with AngularJS

Currently, I am embarking on the development of an Android application using Cordova. To interact with the service end-point of a Drupal website, I have opted to utilize AngularJS for data fetching and manipulation. Initially, my attempt to incorporate ngR ...

Automatically trigger the expansion of all panels within Vuetify using code

I'm attempting to use Vuetify 2.3.5 to programmatically control the opening and closing of expansion panels. <v-expansion-panels accordion> <v-expansion-panel v-for="(item,i) in faqs" :key="i"> <div class ...

Display JSON on the screen so it can be easily copied and pasted

I have a unique challenge where I need to output some Javascript code on the browser screen for easy transfer to another program. Currently, I am utilizing JSON.stringify() from the json2.js library. However, this method is not correctly escaping characte ...

Combining JSON in a unique way on Android

Two JSON objects have been created as follows: Array One: [ { "id":255, "is_new":0, "is_checked":true, "name":"Towel Rack 650", "is_favourite":false }, { "id":257, "is_new":0, "is_checked":true, ...

Printing without sufficient paper will result in an incomplete printout

https://i.stack.imgur.com/jNlRr.jpg I am facing an issue with printing the last column "Potensi". The text in this column is not fully printed. How can I resolve this problem? I am using PHP. Thank you ...

Transferring an array via AJAX to PHP script

After creating an array from a php loop, here's how it looks: echo '<input type="checkbox" name="types[]" id="types[]" value="' . $id . '"> ' . $type . '<br>'; Initially, everything was working fine with jus ...

Cloud Firestore trigger fails to activate Cloud function

I am facing an issue with triggering a Cloud Function using the Cloud Firestore trigger. The function is supposed to perform a full export of my sub collection 'reviews' every time a new document is added to it. Despite deploying the function suc ...

Obtain the index by clicking on an element within an HTMLCollection

Within my HTML code, I have 9 <div> elements with the class ".square". I am looking to make these divs clickable in order to track how many times each one is clicked and store that information in an array. For example, if the fifth <div> is c ...

JavaScript overlay that does not interact with HTML elements directly

Currently, I am facing the challenge of implementing a javascript overlay upon page load without direct access to the html code. My only options are to upload .js and .css files. I have extensively searched for solutions, but as someone with limited exper ...

Updating information within a for loop with jQuery in a Django environment

I'm currently developing a website that enables users to search for papers and interact with them by liking or disliking. The like count should update dynamically as users click the like button. To handle the dynamic updating of the like count, I&apo ...

Leveraging jQuery to extract a key-value pair and assign it to a new property by

I'm struggling with extracting a value from a key-value pair and inserting it into the rel property of an anchor tag. Even though I try to split the code and place the value correctly, it doesn't seem to work as expected. Instead of applying the ...

What is the best way to incorporate a dropdown header in Material-UI on a React project?

I am facing an issue where only the last Menu Dropdown is rendering, but I actually need different Menus to be displayed (with the text faintly appearing behind them). I am uncertain about how to correctly pass the props/state to make this work. import Rea ...

Update array of hotel room reservations using Mongoose

I am currently developing a hotel room reservation system and have defined the attributes in the Room model as follows: rId: String, allocation: [{ date: Number, // 210403 == 2021-04-03 slots: [{ type: mongoo ...

Ways to split text across lines within my list

I am currently developing a shopping list app and everything is running smoothly. However, I am encountering an issue with breaking a long string into the next line. Even though I tried using word-wrap, it doesn't seem to work as intended. For exampl ...

Struggling to convert a JSON response into an object model using TypeScript in Angular?

I'm encountering a problem when trying to convert a JSON response into an object. All the properties of my object are being treated as strings, is that normal? Below is my AJAX request: public fetchSingle = (keys: any[]): Observable<Medal> =&g ...

Is there a similar alternative to {useLocation} provided by 'react-router-dom' that can be used in Next.js?

import { useLocation } from 'react-router-dom'; Currently utilizing Nextjs, I'm seeking assistance in finding an alternative for useLocation ` import Link from 'next/link'; import { FC } from 'react'; import {useRout ...

Passing props from a parent component to a nested child component in Vue 3

My goal is to achieve the functionality described in the title. Suppose I have the following structure: parent -> child -> secondChild Currently, there is a variable called isActive in the parent component. Below is how it can be implemented: paren ...

Unable to display the retrieved list data using v-for loop from axios get request

I recently started using Vue.js and decided to create a simple HTML website with Vue.js to display data from myphpadmin using axios. Everything was working smoothly until I encountered an issue where I couldn't display the JSON message on my screen. n ...

Displaying the servlet response within an iframe

This is the content of Content.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> &l ...