Incorporate additional input fields into a dynamic form using Angular 2+

Currently, I am working with reactive forms and I have a requirement to dynamically add or remove a field from my form upon clicking a button. To better illustrate my goal, here is a prototype example:

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

Essentially, when the + button is clicked, another selection field identical to the first one will appear. Conversely, clicking on the - button will remove the field.

Answer №1

Referencing this tutorial link

You can use the same approach:

form.html

<div formArrayName="hobbies">
          <h4>Your Hobbies</h4>
          <button
            class="btn btn-default"
            type="button"
            (click)="onAddHobby()">Add Hobby</button>
          <div
            class="form-group"
            *ngFor="let hobbyControl of signupForm.get('hobbies').controls; let i = index">
            <input type="text" class="form-control" [formControlName]="i">
          </div>
        </div>

form.ts

this.signupForm = new FormGroup({
      'userData': new FormGroup({
        'username': new FormControl(null, [Validators.required, this.forbiddenNames.bind(this)]),
        'email': new FormControl(null, [Validators.required, Validators.email], this.forbiddenEmails)
      }),
      'gender': new FormControl('male'),
      'hobbies': new FormArray([])
    });

onAddHobby() {
    const control = new FormControl(null, Validators.required);
    (<FormArray>this.signupForm.get('hobbies')).push(control);
  }

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

What are the steps to enable readonly or disabled functionality in Ionic 2?

Trying to make a field readonly or disabled in an ionic2 form: <ion-item> <ion-label fixed>Category <ion-icon name="ios-arrow-forward"></ion-icon></ion-label> <ion-input type="text" [disabled]="false" id="category_ ...

Error: The `prisma.roomMember.create()` function call is not valid

Whenever I try to generate a room without adding a RoomMember, everything goes smoothly. However, the moment I attempt to include a member using the createRoomAction function, an error message pops up: Error Message: Invalid prisma.roomMember.create( ...

Type definition for Angular 7 ngrx Actions

I have a dynamic action that changes the current configuration: export class UpdateConfig implements Action { readonly type = ActionTypes.UpdateConfig; constructor(public payload: { key: string, value: any }) {} } The key parameter is the dynamic ke ...

Error: The Typescript module in Angular 2 does not have the constant 'FORM_DIRECTIVES' available for export

I need to integrate an existing component into my app, but I am facing some issues with the dependencies. Originally, the sample code provided me with these dependencies: import {CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass} from 'angular2/common'; ...

How can one resolve the org.springframework.web.bind.MissingServletRequestParameterException error that occurs in a spring boot and angular application?

I'm currently facing an issue with sending a post request from my Angular 9 app to Spring Boot. Below is the code for the post request: public createSuccessMessage(userId: number, tripName: string): Observable<any> { return this.http.p ...

Typescript failing to indicate that an object may be null or undefined

I can't seem to get TypeScript to recognize that types with | null are nullable. Take a look at the example below where I define the type: type A = { b: { c: number; d: string; } | null; }; When I hover over b, it doesn't ...

There seems to be an issue with the data not reaching the backend

When I submit an HTML form in my application, I am able to see the submitted data in the console before sending the HTTP request from the Angular front end. However, the data is not reaching the backend in NodeJS. Strangely, the code works fine when I su ...

Difficulty resolving paths is a common issue when working with Typescript and Gatsby, but fortunately, VS Code is able to

In my code, I often have imports like import Navi from 'components/Navi' Initially, there is a red error line under the components/Navi section until I include this configuration in my tsconfig.json "baseUrl": "./", "paths": { "components/*": ...

RangeError: The React application has surpassed the maximum stack size limit, causing an error to be thrown

Hey there, I could use a hand. I'm fairly new to React and attempting to develop an application for managing contacts by adding them to Local Storage and deleting them. Below is the code snippet from my App.js file: import React, {useState, useEffect} ...

The environment production variable is perpetually set to true within the app.module.ts file

I'm currently facing an issue with setting a configuration in my app.module file that should differ based on whether I'm in production or not. Within my environment.ts file, I have the following: export const environment = { production: false ...

The error message from TypeScript that states "Cannot read property 'addEventListener'"

Currently delving into the world of TypeScript and following a step-by-step tutorial on Youtube. Despite my best efforts, I keep encountering an error. Uncaught TypeError: Cannot read property 'addEventListener' of null I've rewritten the ...

Incorporate personalized elements into your @react-three/fiber environment

My dilemma lies in the fact that I am trying to incorporate my custom components into my scene. However, these custom components are defined in a separate file. When I attempt to define my custom component, I encounter an error message stating: Cannot find ...

Tips for updating the value within a textfield in HTML

I am looking to dynamically update the value displayed in my Revenue textfield by subtracting the Cost of Goods from the Sales Price. I have included an image of the current layout for reference, but I want the Revenue field to reflect the updated value af ...

Utilizing child component HTTP responses within a parent component in Angular: a comprehensive guide

As a newcomer to Angular, I find myself struggling with http requests in my application. The issue arises when I have component A responsible for retrieving a list of IDs that need to be accessed by multiple other components. In component B, I attempted t ...

Displaying a collection of nested objects in AngularRendering a group

Is there a way to render an object of objects in Angular without converting it into an array or similar structure? I have a large object of objects and I want to avoid multiple iterations through object-to-array conversions just to loop through the array i ...

The module './product-list/product-list.component' could not be located

As a beginner in Angular, I decided to incorporate a top-bar component into my project by following the structure outlined in the app directory. However, I encountered some issues as indicated by the error message that kept popping up. Despite importing ...

Tips for ensuring that CSS hover effects stay in place even when the page is scrolled

i'm having trouble with a project in React JS that I received from another team. I'm not very confident in my skills with React JS, and I'm facing an issue where a certain part of the page is supposed to change to red when hovered over. Howe ...

Learning the process of configuring neo4j connection details without relying on environment variables

Is there a way to specify the database connection in code using the Drivine neo4j driver without relying on environment variables? ...

Refreshing the route in Angular 6 using a partial component

I am developing an app that offers courses in both English and French. My goal is to create a language dropdown header component that will be visible across all pages of the program. When a user selects a different language from the dropdown, I want the fo ...

What is the most effective method for transforming multiple files using the TypeScript Compiler API?

If we have multiple .ts files containing various classes, is there an elegant method to extract portions of each file's AST, modify them, combine them into a new AST, and save it as a new .ts file? Updated 2020-03-08: In other words, is it feasible ...