Angular 4: Utilizing reactive forms for dynamic addition and removal of elements in a string array

I am looking for a way to modify a reactive form so that it can add and delete fields to a string array dynamically. Currently, I am using a FormArray but it adds the new items as objects rather than just simple strings in the array. Here is an example of my current implementation:

ngOnInit() {
  this.form = this.formBuilder.group({
    user: '',
    directory: '',
    filenames: this.formBuilder.array([ this.createItem() ])
  });
}

createItem(): FormGroup {
  return this.formBuilder.group({
    filename: ''
  });
}

Answer №1

Here is an alternative approach to creating a formGroup:

constructor(private formBuilder:FormBuilder){
   this.form = this.formBuilder.group({
    user: '',
    directory: '',
    filename: new FormArray([new FormControl('hello')])
  });

 }

 addFormInput(){
    const form=new FormControl('');
   (<FormArray>this.form.controls['filename']).push(form);
  }

removeFormInput(i){
  (<FormArray>this.form.get('filename')).removeAt(i);
 }

You can see an example in action here: https://stackblitz.com/edit/angular-tvuksw

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

Simple method for extracting data from JSON and saving it into an array with jQuery

I have a JSON file containing the resource "A" and literals "B", "C", and "D". My goal is to extract only the items B, C, and D, convert them into strings, and store them in an array. Below is the script I have written for this purpose: <script> // ...

Is there a similar alternative to ignoring in webpack or browserify?

My code works perfectly in the browser after ignoring two packages with browserify: browserify files.js -i fs-extra -i request --standalone files > files.browserify.js. However, when I try to use webpack instead, the code throws errors about missing mod ...

What sets 'babel-plugin-module-resolver' apart from 'tsconfig-paths'?

After coming across a SSR demo (React+typescript+Next.js) that utilizes two plugins, I found myself wondering why exactly it needs both of them. In my opinion, these two plugins seem to serve the same purpose. Can anyone provide insight as to why this is? ...

Having trouble importing a module in my Node.js/Express application

I've encountered an issue while trying to import files into my node js server file. My usual method is correct in terms of paths, so I'm puzzled about what the error might be. import express from 'express' import mongoose from 'mon ...

Getting a "SyntaxError: Unexpected end of input" error while using jQuery ajax with valid JSON

The PHP response in JSON format shows: {"success":0,"message":"Error: No entityId passed!"} However, my JavaScript code throws an error "SyntaxError: Unexpected end of input". PHP: ... //check if an image id was passed for removal in the POST ...

Develop an object's attribute using form in the Angular 5 framework

I am looking to create an object for a location that includes two parameters. While I can easily create an array of strings using FormGroup, I am unsure of how to create an object with two parameters nested inside it. Below is the code snippet I currently ...

Unable to utilize vue-cookies library in TypeScript environment

I have integrated vue-cookies into my app in the main.ts file: import VueCookies from 'vue-cookies'; ... const app = createApp(App) .use(IonicVue) .use(router) .use(VueCookies,{ expires: '30d', }); Despite adding the cookie v ...

NG Serve crashes after the second modification in the code

The project currently employs Angular 12.1.2. Running ng version produces the following output: Angular CLI: 12.1.2 Node: 14.17.0 Package Manager: yarn 1.22.5 OS: win32 x64 Angular: 12.1.2 ... animations, cdk, cli, common, compiler, compiler-cli, core ... ...

Executing a function in the constructor of an Angular4 component

I am currently facing an issue where I am attempting to invoke a modal function within the constructor in Angular 4. However, it seems that the function is not being called properly as it gets highlighted. Upon loading the page, no errors are logged and th ...

Regex: Enabling commas in the name of an Excel file

My JavaScript code is set up to extract data from an excel file. As a first step, I define a regular expression and assign it to a variable named regex var regex = /^([a-zA-Z0-9\s_!()\\.\-:])+(.xls|.xlsx)$/; Following this, there is s ...

What is the process of obtaining the ID and displaying the subsequent field based on that ID in Ruby on Rails?

I'm utilizing rails4 and I am looking for a more efficient way to display the sub-category list based on the category selected in a form. Currently, I have used JavaScript for this functionality but I believe there may be a better solution. Any sugges ...

Summoning within a rigorous mode

I am facing an issue with my configuration object: jwtOptionsProvider.config({ tokenGetter: (store) => { return store.get('token'); }, whiteListedDomains: ['localhost'] }); In strict mode, I ...

Guide on running PHP (WAMP Server) and Angular 2 (Typescript with Node.js) concurrently on a local PC

My goal is to create a Web app utilizing PHP as the server-side language and Angular 2 as the MVC framework. While researching Angular 2, I discovered that it is best practice to install Node.js and npm first since Angular 2 utilizes Typescript. Despite ha ...

Executing axios calls within other axios calls and altering state in React before all calls have completed

Currently, I am working on implementing nested axios calls to create the desired object by making multiple API requests. However, I am facing an issue where the state updates before all requests have finished, causing my table to populate entry by entry ...

Implementing conditional put on DynamoDB - step by step guide

In my restaurant / bar, I have a DynamoDB table named Cheque to keep track of the cheques for each table. I need to apply certain conditions when creating a new entry in this table: tableNumber should not already exist restaurantId should not already exi ...

Is there a way to identify the Xpath after clicking a button that adds a row to the JQGrid?

Seeking the Xpath for the Row that was added upon clicking a button. Need to click on the datepicker in the first row and first column to select a date. How can I locate the Xpath for this date picker element? See my code snippet below `<table ...

Arrange a div close to another div with the help of absolute positioning

My goal is to create a tooltip-like positioning for an element within the same container as another element. When clicked, this particular element will display a div containing a table. You can find the complete code here: http://jsbin.com/xihebol When s ...

A guide to efficiently fetch JSON data synchronously using AngularJS

Trying to fetch data from a JSON file using AngularJS results in an error due to the asynchronous nature of the call. The code moves on to the next step before receiving the data, causing issues. The $http.get method was used. $http.get('job.json&apo ...

Organizing and managing one-on-one table tennis matches using a customized data structure. Leveraging the power of Vue, JavaScript, and

Seeking advice on the best approach for storing table tennis match data in a web application. I currently have a method in place that works, but I'm open to suggestions for improvement. Here is my current idea: matches: [ { id: 1 datePlayed ...

Mongoose throws a "Possibly unhandled rejection" error when trying to use ContactList.insert as it is not a recognized function

Currently working on a small project using the MEAN stack, but encountering an issue with sending a post request where console.log displays an error. Error Message: Possibly unhandled rejection: {"data":"TypeError: ContactList.insert is not a function S ...