How to generate an interactive text-box using Angular 8 and connecting the input to the component during form submission

When I attempt to add a dynamic text box after clicking a button, the text box is successfully added. However, I am facing an issue where I am unable to retrieve all the values (values of dynamically added text boxes) when the form is submitted. It seems to only bind the value of the last updated text box. Below is a snippet of my code:

contribute.component.ts

export class ContributeComponent implements OnInit {
categories = [];
contribute = {};
private options = [{ value: '' }];
private contributeForm: FormGroup;
constructor(private formBuilder: FormBuilder) {}

ngOnInit() {
this.contributeForm = this.formBuilder.group({
  question: new FormControl(),
  category: new FormControl(),
  options: new FormControl()
});
add() {
this.options.push({ value: this.contributeForm.controls.options.value });
}

And in my HTML file, contribute.component.html

<form [formGroup]="contributeForm" (ngSubmit)="onSubmit(contributeForm.value)">
<div class="form-group">
                <label class="control-label col-sm-2" for="message">Options:</label>
                <div class="col-sm-10 inputGroupContainer">
                    <div *ngFor="let option of options; let in=index" class="spacer">
                        <div class="input-group">
                            <span class="input-group-addon">Option {{in+1}}</span>
                            <input type="text" class="form-control" rows="4" placeholder="Type your option here"
                                formControlName="options" name="option" [value]="options[in].value"/>
                        </div>
                    </div>
                </div>

                <div class="row"></div>

                <div class="col-sm-12 pull-right">
                    <div class="col-sm-4"></div>
                    <div class="col-sm-4">
                        <button class="btn btn-warning" type="button" (click)="add()">Add option <span
                                class="glyphicon glyphicon-send"></span>
                        </button>
                    </div>
                    <div class="col-sm-4"></div>
                </div>
            </div>

Answer №1

It seems like there might be some confusion about how this functionality should work. Your contributeForm currently only allows for a single options field to be bound, meaning you can only assign one value at a time. Perhaps considering turning it into an array would be more appropriate.

Each time the add() function is triggered, it will capture the current value of options. Since options is linked to a single text box, it will always be associated with the most recent one added, typically the last text box at the bottom. Therefore, whenever a new option is added, it will be the one that options is connected to.

If you'd like to see a demonstration, check out this StackBlitz example and observe the console each time a new option is added.

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

Clicking on the image in Angular does not result in the comments being displayed as expected

I find it incredibly frustrating that the code snippet below is not working as intended. This particular piece of code was directly copied and pasted from an online Angular course I am currently taking. The objective of this code is to display a card view ...

Discover the secret to extracting a unique style from inspect mode and incorporating it into your CSS design

I'm currently working on my angular project and I've imported the ngx-editor. My goal is to reduce the height of the editor, but I'm facing some challenges. After inspecting the element, I was able to adjust the height successfully within th ...

The latest update of WebStorm in 2016.3 has brought to light an error related to the experimental support for decorators, which may undergo changes in forthcoming

Hello, I recently updated to the latest WebStorm version and encountered this error message: Error:(52, 14) TS1219:Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' ...

What is the best way to assign a type based on a variadic type in TypeScript?

TypeScript playground link For my current project, I am designing a custom route handler creator for Express. The goal is to allow passing arbitrary assertions as initial arguments before invoking the route handler callback. Here's an example of how ...

What are the benefits of incorporating NgRx in Angular, even when data is consistently synchronized through two-way data binding?

NgRx, analogous to Redux in React, is a tool used for state management in Angular. While state management can become convoluted in React projects, Angular typically avoids this issue thanks to its two-way data binding synchronization. Interestingly, many ...

Warning: Typescript is unable to locate the specified module, which may result

When it comes to importing an Icon, the following code is what I am currently using: import Icon from "!svg-react-loader?name=Icon!../images/svg/item-thumbnail.svg" When working in Visual Studio Code 1.25.1, a warning from tslint appears: [ts] Cannot ...

Unit Testing Sentry with Jest Framework using TypeScript in a Node.js Environment

I'm in the process of integrating Sentry into my existing NodeJS project, but I'm facing an issue with mocking a specific part of the Sentry code. Here's the relevant Sentry code snippet: const app: express.Express = express(); Sentry.init ...

How can I implement a master-detail view in Angular 2?

Update: I finally figured it out. After moving all the html from index.html to app.component.ts, everything started working perfectly. The method described below is the correct one. I've been facing an issue where I have a ParentComponent that retrie ...

Error in Node.js with MongoDB: Array of OptionalId<Document> Typescript typings

I have successfully established a connection and written to my MongoDB collection, but I am encountering a type error that is causing some confusion. Below is the code snippet along with the error message: interface Movie { id: number; title: string; ...

Creating a type or interface within a class in TypeScript allows for encapsulation of

I have a situation where I am trying to optimize my code by defining a derivative type inside a generic class in TypeScript. The goal is to avoid writing the derivative type every time, but I keep running into an error. Here is the current version that is ...

What is the best method for retrieving GET parameters in an Angular2 application?

Is there a way in Angular2 to retrieve GET parameters and store them locally similar to how sessions are handled in PHP? GET Params URL I need to obtain the access_token before navigating to the Dashboard component, which makes secure REST Webservice cal ...

While using axios to make a GET request, I encountered errors when checking for .isSuccess in react

const searchInvoiceList = async ( plantLocation: string, invoiceType: string ) => { let dataList: InvoiceData[] = []; await axios .get(`${linkURL}inv/getControlList/${plantLocation}/${invoiceType}`) .then((response) => { dataLis ...

Finding the right way to cancel a Firestore stream within a Vue component using the onInvalidate callback

Currently, I am utilizing Vue 3 to develop a Firebase composable that is responsible for subscribing to an onSnapshot() stream. I have been attempting to unsubscribe from this stream by invoking the returned unsubscribe() function within both watchEffect ...

Protractor syncing with an Angular page following redirection to an Auth0 non-Angular page

My Angular web application utilizes Protractor for end-to-end tests. Recently, I implemented OAuth0 authentication into my app. To disable Angular synchronization before redirecting to the non-Angular OAuth0 page, I use await browser.waitForAngularEnabled( ...

Omit assets in final version

During development (ng serve), I have specific assets like images and styles that I use. These assets are not needed in the production build as they are provided by a CDN. My requirements are: When using ng serve, I want to serve files from the folder . ...

The use of p-message in Angular's PrimeNg library is not permitted

Hey there, I'm having a bit of trouble with the p-message Tag in Angular. I believe I've imported it correctly as shown below. import { MessageModule } from 'primeng/message'; imports: [ .... MessageModule, ... In the ...

An error message occurs in TypeScript when trying to access a property that does not exist in an array

I'm having trouble figuring out this issue... I am receiving data from an API and storing it as an array. I'm attempting to access the data in this format... this.data.results[i].datas[j].dataType However, I keep getting the error "property res ...

Creating comprehensive and elaborate intellisense documentation for Typescript Union Types

When we call the baz function with the code provided, the typeahead will display 'a' and 'b' as potential values. https://i.stack.imgur.com/SrKo7.png If additional documentation is needed for each of these values, how can it be accomp ...

Update the input for a component within the ngOnChanges method, and ensure that the OnPush change

I've encountered an issue with my Angular 6 application: The Dilemma Imagine I have two components: parent and child. The child component has two inputs. When one input changes, the child emits something to the parent within the ngOnChanges() lifec ...

Issue encountered in NestJS/TypeORM: Unable to modify the property metadata of #<Repository> as it only has a getter method

When attempting to launch my nestjstutorial app, I encountered the following error message. The backend is connected to a PostgreSQL database. TypeError: Cannot set property metadata of # which has only a getter at EntityManager.getCustomRepository (D:&b ...