Display the values from form fields in Angular2 after dynamically adding them

I am struggling to output the values of each object in the choices array using console log. Despite being able to display the objects in the choices array, all the values appear empty. Every object is showing as

timeZonePicker: "", startTimeInput: "", endTimeInput: ""
. Although I can add and remove items from the choices array and successfully log the keys, logging the values has proven to be a challenge. I have experimented with various methods without achieving the desired outcome.

<div class="container">
    <div class="row">
        <div class="col-md-9">
            <div *ngFor="let choice of choices; trackBy=customTrackBy" class="form-inline">
                <select [ngModel]="choice.timeZonePicker" class="form-control" id="timeZonePicker">
                    <option *ngFor="let timeZone of timeZones" [selected]="timeZone.chosenTimeZone == '(GMT) Western Europe Time, London, Lisbon, Casablanca, Greenwich'">{{ timeZone.chosenTimeZone }}</option>
                </select>
                    <input [ngModel]="choice.startTimeInput" type="time" class="form-control" id="startTimeInput">
                    <input [ngModel]="choice.endTimeInput" type="time" class="form-control" id="endTimeInput">
            </div> <!-- end form field div -->
            <div class="container">
                <button (click)="onSubmit()" class="btn btn-primary">Submit</button>
            </div>
            <div class="container">
                <button class="pull-left btn btn-success" (click)="addNewChoice()">Add Field</button>
                <button class="pull-left btn btn-danger" (click)="removeChoice()">Remove Field</button>
            </div>
        </div> <!-- end col-md-9 -->
    </div> <!-- end row -->
</div> <!-- end container -->

Here is the related component code:

export class TimeZonesComponent {
constructor(){}

timeZones = [ 
        { val: -12, chosenTimeZone: '(GMT -12:00) Eniwetok, Kwajalein'},
        { val: -11, chosenTimeZone: '(GMT -11:00) Midway Island, Samoa'},....];

choices = [
    {
    timeZonePicker: '',
    startTimeInput: '',
    endTimeInput: ''
    }, 
    {         
    timeZonePicker: '',
    startTimeInput: '',
    endTimeInput: ''
    }];

addNewChoice(){
    var dataObj = {           
        timeZonePicker: '',
        startTimeInput: '',
        endTimeInput: ''
    };
    this.choices.push(dataObj);
}

removeChoice(){
    var lastItem = this.choices.length - 1;
    this.choices.splice(lastItem);
    console.log(this.choices);
}

onSubmit(){  
    console.log(this.choices);  
}

customTrackBy(index: number, obj: any){
    return index;
}
}

Your assistance with this issue would be greatly appreciated.

Answer №1

After some troubleshooting, I discovered my mistake. It turns out that I forgot to implement trackBy and [(ngModel)] in my code. Initially, I was only using one-way binding when in fact I needed two-way binding for the functionality to work correctly. If anyone is interested in examining the code for educational purposes, feel free to leave a comment and I will gladly provide it.

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

The TypeScript compiler encounters difficulties in locating type definitions when utilizing an inherited tsconfig file

There seems to be an issue with the functionality of tsconfig.json inheritance, specifically regarding the proper inheritance of the "typeRoots" setting. http://www.typescriptlang.org/docs/handbook/tsconfig-json.html (folder structure provided below) we ...

Unable to display content within the router-outlet

I'm currently attempting to dynamically change the router outlet based on authentication status. My code looks something like this: <div *ngIf="isLoggedIn" class="layout-wrapper layout-2" [ngClass]="{'layout-loading&ap ...

Launching a centered pop-up window to display a submitted form message

I am attempting to create a page that displays a confirmation message in a center-aligned pop-up window after the user submits a form. I have managed to open the page in a pop-up window, but I am struggling to center the window using my current code (I pre ...

Encountered an unexpected token error in react-leaflet while attempting to render the component for a unit test scenario

Error in running test suite An unexpected token was encountered by Jest Jest failed to parse a file due to non-standard JavaScript syntax used in the code or its dependencies, or when Jest does not support such syntax configurations. SyntaxError: Unexpe ...

Explain what one-time typescript interfaces are

As someone who has been using React for quite some time, I am now looking to integrate Typescript into my projects. In the past, I would create large "container" objects like this: const theme = { colors: { primary: '#00f', accent: &ap ...

"Troubleshooting problem with aligning divs in Angular using

I need to design a grid layout for displaying cards with responsiveness, adjusting the number of cards per row as needed. I am currently using angularfxlayout, but facing an issue where the divs are not aligned properly between rows. Current Layout: http ...

Exploring Angular 4's Capabilities: Navigating a Multi-Dimensional Array

I am currently working with a multi-dimensional array that has two keys, and it is structured as follows: user: any = {}; // The index is incremented within a for loop to add values to the user object (this part is functioning correctly) this.user[index++ ...

Quick way to specify type for Observable in Typescript

Exploring Shortcut Declarations When working with TypeScript, I often take a shortcut when declaring object shapes. Instead of creating an interface first and then specifying that the object conforms to that type, I simply do: object: { fizz: boolean, buz ...

React Typescript: excluding a property in a higher order component

Is it possible to write Typescript type definitions that properly expose the Props type of a component created by a HOC? I want to infer the type of props of the wrapped component and remove any properties provided by the HOC. For example, if we have a HO ...

What is the proper way to utilize bootstrap dropdown menus?

I need to create a dropdown menu similar to the one shown in this image: https://i.sstatic.net/SXDgy.png https://i.sstatic.net/wVbnd.png I attempted to use code from the following URL: https://getbootstrap.com/docs/4.0/components/dropdowns/, but unfortun ...

Angular 10 - Timezone Detection and Interactive Calendar

I am encountering a major issue with the Angular DateTimePicker and TimeZone functionality. I need to dynamically switch the TimeZone at runtime in my component. Every date displayed on the frontend must be converted, while every date sent to the backend n ...

TS6059 found in excluded folder

I'm facing an issue with my tsconfig.json file that looks like this: {"compilerOptions": { "module": "commonjs", ...

Typescript feature: Configuring BaseUrl with nested directories

When utilizing the 'baseUrl' property along with the 'paths' property in this manner: "baseUrl": "./src", "paths": { "app-component": [ "app/app.component"], "test-component": [ "app/test/test.component" ] } the compilation proces ...

Guide to Binding Query Parameters to Input Fields in Angular 8

Currently, I am working on a search page that features an input field, similar to the one showcased in the Angular documentation (https://angular.io/tutorial/toh-pt6#search-by-name). Whenever a user enters a search term in this input field, an ajax request ...

Improving the method to change a string into a string literal in TypeScript

Utilizing a third-party tool that has specified editorStylingMode?: 'outlined' | 'underlined' | 'filled'; I have set the value in my environment.ts file (in Angular) as shown below export const environment = { productio ...

An error occurred during the npm installation process of @angular/cli due to an unexpected JSON input termination around "...ain" : "src/index.js"

Upon running the npm install -g @angular/cli command, I encountered the error mentioned above. The detailed logs are provided below: verbose stack SyntaxError: Unexpected end of JSON input while parsing near '...ain" : "src/index.js"&ap ...

A step-by-step guide to thoroughly examining the form status in a React application, allowing for the activation of a previously disabled submit button

When I have an onChange event in React, the state is populated correctly. I disable the form button when a field is empty on submit, but I also want users to be able to go back and fill out those fields. The key issue is that if both fields have data, I wa ...

Troubleshooting Primevue Data table styling issues in Vue3

Currently, I am attempting to incorporate grids into my data table using primevue library. However, despite following the provided example at https://www.primefaces.org/primevue/datatable/dynamiccolumns, the gridlines are not appearing on the table. The c ...

md-table Using FirebaseListObservable as a DataSource

I am currently working with a FirebaseListObservable and a BehaviorSubject that is listening for an input filter. The goal now is to merge these two entities in order to return an array that has been filtered based on the input value, which will then be us ...

Encountering an issue where the useMutation function is not recognized on the DecorateProcedure<MutationProcedure> type while attempting to utilize the useMutation feature

Currently, I am utilizing the NextJS app router. I am attempting to invoke a rather straightforward route: import { z } from "zod"; import { createTRPCRouter, publicProcedure } from "~/server/api/trpc"; // document sending user email to waitlist da ...