Creating a new element in the DOM when a button is clicked using Angular 2+

Greetings! I am currently in the process of learning how to manipulate the DOM using Angular 2+ and my goal is to incorporate an Input field with type email when the click event is activated. Despite conducting some research via Google, I have been unable to find a solution that aligns with Angular2+.

<form>
<fieldset>
  <legend>
    <span class="number">3</span>E-Mail Receipants</legend>
  <input type="email" name="email1" placeholder="Email Recipients <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dab0b5b2b4f4beb5bf9ab7bbb3b6f4b9b5b7">[email protected]</a>">
  <input type="button" value="Add Email" (click)="addInputEmail()">
</fieldset>
<input type="submit" value="Generate Template" />

My primary concern is understanding how I can generate additional input fields beneath the pre-existing one. What tools are available for me to utilize within this context?

addInputEmail(){
}

Essentially, I would like a new input field to be created every time the button is clicked. Unfortunately, I feel lost as I am uncertain about the 'Tools' needed to effectively manipulate it initially.

Many thanks in advance.

Answer №1

Here is a solution that should do the trick --

 <div *ngFor='let email of emails'>
   <input type="email" [attr.name]="email" >
 </div>
 <input type="button" value="Add E-Mail" (click)="addInputEmail()">

--

export class formComponent {
  emails = ["email1"];
  emailNumber = 1;
  constructor () {

  }

  addInputEmail() {
    this.emailNumber++; 
    this.emails.push("email"+this.emailNumber)
  }
}

I hope this explanation helps.

This code dynamically generates input elements based on the array of emails. When you click the button, it adds a new entry to the array which in turn creates a new input field in the template.

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 promise briefly returns a placeholder object before resolving with the actual response

Currently, I am working on a simple check to determine whether myAnswer contains an answer. The checking functionality is operating smoothly; however, the issue arises in the final function that aims to return the string obtained from myAnswer. Instead of ...

Creating new routes and lazy-loading in Angular CLI page generator

I have questions regarding the process of page generation and route creation by the CLI. When a new page is generated using the ng CLI, it creates the page module, HTML, spec, and SCSS files, as well as updates the routing module. 1) By default, the page ...

When compiling for production, I am encountering an issue where the hashed files are resulting in 404 errors for users when they try to refresh. I am unsure of the best

My Angular app is hosted on GCP storage. When I use the command ng build --prod --base-href . --output-path ~/Dev/GCP/, everything works perfectly except for one issue. If a user refreshes to get new content, they encounter 404 errors on CSS and JavaScript ...

Experiencing a Typescript error when trying to access a property within a nested object

My current challenge involves typing an object, which seems to be error-free until I try to access a nested property and encounter the dreaded red squiggle. After some research, I came across suggestions like this: type FlagValue = string | boolean | numb ...

Issues with running NPM script for compiling TypeScript code

[UPDATE] Initially, I resolved this issue by uninstalling tsc using npm uninstall tsc (as recommended in the response marked as the answer). However, the problem resurfaced after some time, and eventually, I found success by utilizing Windows Server for L ...

Encountering a "subscribe is not a function" error while attempting to utilize a JSON file in Angular 2

My attempt to import a JSON file into my service is resulting in the following error: Error: Uncaught (in promise): TypeError: this._qs.getBasicInfo(...).subscribe is not a function(…) The current state of my service file is as follows @Injectable() ...

The 'Element[]' type is lacking certain properties when dealing with react children

In my code, there is a parent component passing down its children to a child component. These children can be either single nodes or arrays of nodes, and the ChildComponent renders them differently based on their type. However, when I try to render the Chi ...

Angular: Tailoring the Context Menu

Currently, I am utilizing a helpful tutorial to implement a custom context menu feature. The main issue I am facing is that when a user interacts with the list items, I want the correct index of each item to be displayed. However, at the moment, clicking o ...

Developed a customized checkbox component using React

I encountered an issue while creating a custom checkbox in React. I was able to successfully create it, but faced difficulty in reverting it back to its original state once checked. The values for checked and unchecked are being fetched from a JSON data. ...

The process of expanding a nested node in the Angular Material tree with deeply nested data

Within my Angular 7 application, I am utilizing a mat tree structure that contains nested array objects. The goal is to automatically expand specific nested sections after users make changes to the data within those sections. While I have successfully exp ...

Make leaflet function operate synchronously

There seems to be an issue with calling the setMarker() function within another function, as the markers are not being set. It's possible that this is due to the asynchronous nature of the setMarker() function because of the Promise it uses. getCities ...

Switching the Angular host using @input directive

I am exploring how to modify the appearance of my component using the angular @Input() decorator. The reason for this is because I encountered difficulties in: Modifying the CSS via @ViewChild as it was not initialized at ngOnInit() Applying styles throu ...

Typescript error encountered when executing multiple API calls in a loop causing Internal Server Error

I'm relatively new to Typescript/Javascript and I am working on a function called setBias(). In this function, I want to set all indices of this.articles[i].result equal to the biased rating returned by the function getBiasedRating(this.articles[i].ur ...

Tips for interfacing with Angular ColorPicker elements using Selenium WebDriver

Is there a way to automate interactions with Angular ColorPicker components using Selenium WebDriver? Since there is no text field input for hex codes, it relies solely on mouse clicks. For reference, you can check out this example: https://www.primeface ...

Encountering errors in Angular when trying to access a property that is undefined using

One of the components I've created is being used in its parent component: <app-event-menu-nav [event]="event"></app-event-menu-nav> Below is the code for this component: import {Component, OnInit, ChangeDetectionStrategy, Input} ...

The data in DataTables is loading correctly, however, the buttons and sorting features are not operating as intended within Angular 4

I am currently working on an Angular 4 project where I need to display data in a table format using the DataTables library. While I have successfully implemented the hardcoded examples provided by DataTables with all the buttons functioning as expected, I ...

What is the best way to handle alias components in next.js when using ts-jest?

When working with TypeScript, Next.js, and Jest, I wanted to simplify my imports by using aliases in my tsconfig file instead of long relative paths like "../../..". It worked fine until I introduced Jest, which caused configuration issues. This is a snip ...

Rotate object within HTML table

I have a simple data structure as shown below: [ { "ClientId": 512, "ProductId": 7779, "Date": "2019-01-01", "Quantity": 20.5, "Value": 10.5 }, { "ClientId": 512, "ProductId": ...

Can you advise on how to generate a key to access an environment.ts value within a *ngFor loop? Specifically, I am trying to locate keys that follow the pattern 'environment.{{region}}_couche_url' within the loop

I currently have a block of HTML code that is repeated multiple times. <!-- Metropolitan Map --> <div> <app-map [name] = "(( environment.metropole_name ))" [layer_url] = "(( environment.metropole_layer_url ))" ...

What is the correct way to invoke a function from an external JavaScript file using TypeScript?

We are currently experimenting with incorporating Typescript and Webpack into our existing AngularJS project. While I have managed to generate the webpack bundle, we are facing an issue at runtime where the program is unable to locate certain functions in ...