How to add Input fields dynamically in AngularJS

Manvi Chaddha
Last Updated: May 13, 2022

Introduction

AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop. In this blog, we will use Angular to add input fields dynamically. 
This tutorial will require you to have some familiarity with the Basic Concepts of Angular. If you are new to it, getting familiar with the basics is recommended by referring to our blog- Introduction to AngularJS.
Let’s get started!!

Understanding the Task

Consider that you are using a To-do list app to track your daily activities and tasks you need to perform. You click on the Add Task button, and an input field is generated to add your task. Pretty simple right!!

The process is illustrated in the following gif.

The stepwise breakdown of what is happening is illustrated below:

So now we have a clear understanding of what we are supposed to do, let's start.

Set Up

Step 1) Create an Angular Application using the command ng new my-app. Accept the defaults when the ng new command prompts. The folder structure will look like this:


Step 2) The required component for the operation is created. Components are the main building block for Angular applications. Each component consists of:

  • An HTML template that declares what renders on the page
  • A Typescript class that defines the behavior
  • A CSS selector that defines how the component is used in a template
  • Optionally, CSS styles applied to the template


Use the command ng generate component <component-name>  inside your application's directory to create a new component. 

Note that the new component will be created inside the app folder. The folder structure will look like this:

We are done with the basic setup required. Now let's quickly jump to the implementation part.

Implementation

We have already created the component for the operation, i.e., the add-inputComponent. In this section, we will implement the functionality. 

Step 1) Modify the add-input.component.html file.  As discussed above, all you need to do is add a button in it inside a div. The code is given below:

<center>
    <div class="showInputField"></div>
    <!-- The add() function is called -->
    <button (click)="add()">ADD</button>
 </center>


Note that there is a click event on the button that redirects the control to the user-defined function in the file add-input.component.ts

Step 2) Every time the user clicks on the button, the createElement() method is used to create a division and the innerHTML() property makes an input field.

File:  add-input.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-add-input',
templateUrl: './add-input.component.html',
styleUrls: ['./add-input.component.css']
})
export class AddInputComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
add(){
let row = document.createElement('div');
row.className = 'row';
row.innerHTML = `
<br>
<input type="text">`;
document.querySelector('.showInputField').appendChild(row);
}
}


Step 3) The created div needs to be appended to the main div of the add-input.component.html. The file app.module.ts needs to import the add-input.component as shown below:

Filename: app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AddInputComponent } from './add-input/add-input.component';
@NgModule({
declarations: [
AppComponent,
AddInputComponent
],
imports: [
BrowserModule,
AppRoutingModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }


The output is:

Before clicking the button

After clicking the button

 

Let's look at some of the frequently asked questions.

Frequently Asked Questions

Q1) What is AngularJS? 
Ans 1) AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. AngularJS's data binding and dependency injection eliminate much of the code you would otherwise have to write.

Q2) How does AngularJS work with HTML? 
Ans 2)  AngularJS extends HTML with ng-directives. The ng-app directive defines an AngularJS application. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data. The ng-bind directive binds application data to the HTML view.

Key Takeaways

The blog discussed adding input fields dynamically in detail. But this is not enough, right? It is recommended to explore more about web technologies from our blogs.

A common problem faced by all of us is that we prepare well, but we cannot solve the questions on time during online assessments. To overcome this, Coding Ninjas have developed an online mock test series. The mock tests for leading companies like Amazon, Microsoft, Google, Adobe, Flipkart, TCS, Wipro, and Accenture are free. Our team of experts has curated and designed these online mock test series to help you prepare better for your coding interview rounds. In this online test series, you will get multiple tests that include the latest coding interview questions. . Start preparing for the 2021 Amazon, Microsoft, etc., tech interviews now.

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think