Adding or removing form fields dynamically in Angular2

I have been attempting to dynamically append fields to the choices array upon clicking addNewChoice, but I have not been successful thus far.

<form class="form-inline">
    <fieldset *ngFor="let choice of choices">
        <div class="form-group">           
            <select class="form-control" id="timeZonePicker">
                <option value="-12" >(GMT -12:00) Eniwetok, Kwajalein</option>
                <option value="-11" >(GMT -11:00) Midway Island, Samoa</option>
                    ............
            </select>
        </div>
        <div class="form-group">
            <input type="time" class="form-control" id="startTimeInput">
        </div>
        <div class="form-group">
            <input class="time" class="form-control" id="endTimeInput">
        </div>
    </fieldset>
</form>
    <button class="pull-left btn btn-success" (click)="addNewItem()">Add Field</button>
    <button class="pull-left btn btn-danger" (click)="removeItem()">Remove Field</button>

Below is the component code snippet.

export class TimeZonesComponent {
constructor(){}

choices = [{id: 1}, {id: 2}];

addNewChoice(){
    var newItemNo = this.choices.length + 1;
    this.choices.push({'id': newItemNo});
}

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

I have experimented with various Angular.js solutions without success in Angular2. Any assistance would be greatly appreciated!

Answer №1

There is no addNewItem or removeItem function available.

  <button class="pull-left btn btn-success" (click)="addNewChoice()">Insert Field</button>
  <button class="pull-left btn btn-danger" (click)="removeChoice()">Delete Field</button>

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 test window displays the Angular test component

During my test runs, I have noticed a strange occurrence. Components are appearing in the DOM near where the tests are being conducted. What's even more peculiar is that only one component is visible at a time. This phenomenon seems to occur with ever ...

What is the best way to obtain and transmit an ID from an Angular dropdown menu selection

Can you assist me with a coding issue? In my template, I have a select dropdown with options saved in a list of settings. Each setting has its own unique id. I also have a data model in my interface for fields sent or received from the backend. How can I e ...

Looping inside a loop with Angular's ngFor

I am working on an Angular + Firebase app. Within one of my components, I am retrieving elements from the Firebase DB and binding them into a template using *ngFor: <div *ngFor="let comment of (comments | async)> <div>{{ comment.text }}< ...

Incorporating a custom transpiled file format into Typescript imports

I am trying to import a file format .xyz that does not have fixed types for all instances of the format: import { Comment, Article, User } from "./Blog.xyz" However, I keep getting this error message: TS2307: Cannot find module './Blog.xy ...

Adding *ngIf dynamically within a directive allows for conditional rendering based on certain parameters or

Is there a way to dynamically include an *ngIf on an element that is decorated with an attribute directive? I decided to test this with a simple experiment: @Directive({ selector: '[lhUserHasRights]' }) export class UserHasRightsDirective i ...

What does the concept of "signaling intent" truly signify in relation to TypeScript's read-only properties?

Currently diving into the chapter on objects in the TypeScript Handbook. The handbook highlights the significance of managing expectations when using the readonly properties. Here's a key excerpt: It’s crucial to clarify what readonly truly signif ...

Do we still need to configure XSRF-TOKEN on the server even when using HttpClientXsrfModule?

Would implementing the code below in app.module be sufficient to protect against XSRF/CSRF on the client side? HttpClientXsrfModule.withOptions({ cookieName: 'XSRF-TOKEN', headerName: 'X-XSRF-TOKEN' }) Alternatively, is additional ...

Error message (7027) detected when attempting to clear cells in Excel Office Script due to unreachable code

I'm encountering an issue with a script that is working fine, except for the part where it's supposed to clear the B4:B120 area in the "// Clear the Margin Updates column" section - which is mysteriously greyed out: function main(workbook: ExcelS ...

After upgrading to node version 20 and other dependencies, encountering ERR_REQUIRE_ESM issue

Attempting to update node from version 16 to 20 has led me to also consider upgrading some other libraries simultaneously. Upon trying to start my backend after completing the updates, the following error occurred: % yarn run dev [nodemon] 3.0.1 [nodemon] ...

Structuring a project with React and backend for sharing code

The organization of folders outlined in the structure below for a React frontend and Express backend is really appealing to me: root ├── backend | ├── node_modules | ├── public | ├── src │ │ └── Server.ts | ...

The dropdown menu in Angular 2/4 isn't displaying the selected item

I am currently working on implementing a dropdown feature in my Angular application. The dropdown consists of a list of shops, and when I select a shop, it should display the corresponding content for that shop. However, I've encountered an issue wher ...

Angular 5 offers the ability to incorporate dynamic checkbox input into your application

Here is my code snippet: <input [type]="'checkbox'" [(ngModel)]="inputValue"> <p>Value: {{ inputValue }}</p> I'm puzzled as to why the value in inputValue remains unchanged. Can anyone shed light on this? I am unable to ...

Execute a function when an RXJS Observable has completed its operation

Using the RXJS Observable has been smooth sailing so far, but I now find myself needing to not only react to observer.next() but also when observer.complete() is called. How can I capture the OnComplete event of an RXJS Observable? The documentation for ...

Using formControlName with an Ionic2 checkbox allows for seamless integration of

Currently facing an obstacle with checkboxes in ionic2. Here is how I am using the checkbox: <ion-item> <ion-label>Agree</ion-label> <ion-checkbox color="dark" id="agree" name='agree' class="form-control" formContro ...

What could be the reason behind the Email Form (ASP.net) functioning properly for internal emails but not for external ones?

Although it doesn't seem to be a coding issue, I wanted to ask for help in figuring out why my online form has suddenly stopped delivering emails when an external email address is used. For example, the form works fine with the company email address: ...

Once app.component's ngOnInit is completed, the child's ngOnInit will be triggered in Angular6

I am working on a project where I need to make an API call in the app.component's initialization process. The child component should then wait for the completion of the app.component's ngOnInit() before proceeding. In app.component.ts: ngOnInit ...

The Tailwind CSS class "ring-inset" does not appear to be appearing on iPhone devices when applied to form inputs

I have implemented custom styling for form inputs in my Next.js project using Tailwind CSS classes. Below is the code snippet that showcases how I have styled the form inputs: import * as React from "react"; import { cn } from "@/lib/util&q ...

Vue.js with TypeScript: The property 'xxx' is not found on the type 'never'

I have a computed method that I am trying to execute: get dronesFiltered(){ const filtered = this.drones.filter((drone) => { return drone.id.toString().indexOf(this.filterId) > -1 && drone.name.toLowerCase().toString().in ...

Encountered an issue while implementing Angular Server-Side Rendering with the @nguniversal/express-engine package: an error was triggered (ERROR in error TS6053: File '/project/src/server.ngtypecheck.ts' not

Recently, I have been utilizing @nguniversal/express-engine for Server Side Rendering in Angular. However, when attempting to execute $ nmp build:ssr or $ npm run dev:ssr, I am encountering the following error message. ERROR in error TS6053: File 'C:/ ...

Error message displaying Angular Service not able to be injected into component: StaticInjectorError in AppModule

I'm currently attempting to inject a SpotifyService service into a SearchComponent component, where the service requires Http as a parameter. Below is my module setup: @NgModule({ imports: [ BrowserModule, FormsModule, RouterModule ], decla ...