Add a new child component template with each click using the onclick event in Angular

Is there a way to dynamically add a child component with each button click event?

Here is the HTML code for the button:

<button type="button" class="btn btn-success btn-sm btn-add-phone" (click)="addfield()"><span class="fa fa-plus"></span> </button>

The child component that gets displayed on every button click:

<app-farmer-registration-phone *ngIf="loadComponent"></app-farmer-registration-phone>

Corresponding Component TypeScript file:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-farmer-registration',
  templateUrl: './farmer-registration.component.html',
  styleUrls: ['./farmer-registration.component.css']
})
export class FarmerRegistrationComponent implements OnInit {
public   loadComponent = false;
  constructor() { }

  ngOnInit() {
  }

    addfield(){
        this.loadComponent = true;

    }
}

Answer №1

If you want to iterate over an array in Angular, you can use the *ngFor directive. First, create a temporary array like this:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-farmer-registration',
  templateUrl: './farmer-registration.component.html',
  styleUrls: ['./farmer-registration.component.css']
})
export class FarmerRegistrationComponent implements OnInit {
public   loadComponent:any[] = [];
  constructor() { }

  ngOnInit() {
  }

    addfield(){
        this.loadComponent.push(1);

    }
}

Your HTML code should look like this:

For the button element:

<button type="button" class="btn btn-success btn-sm btn-add-phone" (click)="addfield()"><span class="fa fa-plus"></span> </button>

The child component that will be loaded each time the button is clicked:

<app-farmer-registration-phone *ngFor="let item of loadComponent"></app-farmer-registration-phone>

Answer №2

To implement this functionality, you will need to utilize the ngFor directive.

Start by creating a placeholder array. Then, iterate over this array to dynamically insert child components.

Check out a live demonstration on Stackblitz

Component Code:

arr = [];

addfield() {
  this.arr.push(''); // Add an empty string or any other value
}

HTML Markup:

<div *ngFor="let item of arr">
  <app-farmer-registration-phone></app-farmer-registration- 
   phone>
</div>

<button type="button" class="btn btn-success btn-sm btn-add-phone" (click)="addfield()"><span class="fa fa-plus"></span> </button>

Answer №3

To accomplish this task, you can utilize a for loop in combination with the child component.

Start by assuming an array and then insert new indexes into it whenever the add Button is clicked.

Below is the code snippet to guide you through:

Array

public items = []

public add () {
 this.items = [...this.items, this.items.length]
}

Child Component

<app-farmer-registration-phone *ngFor="let item of items" ></app-farmer-registration-phone>

Check out this demo on StackBlitz

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

Enhancing component and view functionality in Angular

Recently, I started working on Angular 11 and encountered a simple yet challenging question. Despite my best efforts, I have been unable to find a suitable answer. In an attempt to utilize Object-Oriented Programming (OOP) concepts within Angular, I create ...

A step-by-step guide on accessing the data from an uploaded JSON file in a React application

One exciting feature is the drag and drop component that allows users to add multiple files. However, there seems to be an issue with displaying the content of a JSON file once it's added. Below is the code snippet in question: if (files?.length) ...

Issue: The 'async' pipe was not found after updating to AOT and IVY

I recently upgraded my project to AOT compliance and ever since, I've been experiencing issues with the | async pipe in my HTML code. Here is an example of what my HTML looks like: <div *ngIf="(mySubscription$| async) != null"> //some ...

Update the mat-chip-remove positioning attributes

While browsing through the mat-chip documentation, I came across the following information: MatChipRemove Provides proper (click) support and styling for using the Material Design "cancel" icon, which can be found at https://material.io/icons/#ic_cancel. ...

Determining the output type by considering the presence of optional parameters

function customFunction<T>(defaultValue?: T) { return defaultValue; } const definitelyNullOrUndefined = customFunction<string>(); // type: string | undefined const definitelyStringType = customFunction<string>('foobar'); // ...

Exploring the terrain of observable data

Understanding how to filter an observable is really challenging for me right now. I have a gadget {name: string, description: string} I possess an observable collection of gadgets [{},{},{}] My goal is to iterate through my observable collection of ga ...

Angular 6 Subscription Issue: Problems with Variable Assignments

Currently, I am working on a map feature that utilizes the mapbox API and relies on the longitudinal and latitudinal coordinates obtained from a geocoder. There is a particular service in place that calls an endpoint with certain parameters. Upon subscrib ...

Incorporating Angular: A guide to removing a specific element from an HTML array using line breaks

For instance, here is a screenshot of an example: https://i.stack.imgur.com/UlP23.png In the section where I labeled "I want to go down a line", I have an array containing errors related to usernames and passwords. This is how the component.ts file looks ...

How can we set up the Typescript Compiler to recognize typings and modules effectively?

I have been working on a TypeScript project with the following structure: <work folder>/Scripts/ (project root) +-- App +--- subfolder1 +--- subfolder2 +-- typings After openi ...

Issues with IonPicker displaying incorrect values

In my Ionic App, I am using the ion-picker component to display the selected text from an array of options. Although everything seems to be working fine and the console.log accurately displays the index value, there is a strange behavior when it comes to s ...

Customizing Components in Angular 2/4 by Overriding Them from a Different Module

Currently, I am utilizing Angular 4.3 and TypeScript 2.2 for my project. My goal is to develop multiple websites by reusing the same codebase. Although most of the websites will have similar structures, some may require different logic or templates. My p ...

What is the best way to organize objects based on their timestamps?

I am faced with the task of merging two arrays of objects into a single array based on their timestamps. One array contains exact second timestamps, while the other consists of hourly ranges. My goal is to incorporate the 'humidity' values from t ...

Error in Angular 2: Uncaught Promise TypeError - Unable to access property 'title' of undefined

Whenever I attempt to include a text input field with dual binding in my App, the following error pops up: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'title' of undefined TypeError: Cannot read property 'title&ap ...

What is the best method to retrieve the value of a cell in a different cell within the same row in an Angular Material Data-Table?

I am working with an Angular Material Data Table that has four columns. In every row, the last cell contains a button with an on-click function attached to it. I need to pass the value from the first cell ("Name") as a parameter in the corresponding button ...

Is it possible to pass parameters from a base class's constructor to a child class?

I'm facing an issue with my base (generic) classes where the properties are initialized in the constructor. Whenever I try to extend these classes to create more specific ones, I find myself repeating the same parameters from the base class's con ...

There was an issue encountered while compiling the template for 'AppModule'

While attempting to construct an Angular 6 application, I encountered an issue when utilizing the --prod flag. ERROR in Error during template compile of 'AppModule' Expression form not supported in 'reducers' 'reducers' ...

Is it possible to determine if an HTML form has been modified?

Is there a way in typescript to determine if a form has been changed and return true or false accordingly? For example, if I have a first name field with the current value of "John" and then change it to "Johny", it should return true. But if I revert it b ...

Obtaining child elements of the DOM within an Angular Component that has already been instantiated: A step-by-step guide

Imagine I have a component called <app-parent></app-parent>. The corresponding file is named parent.component.ts. Within app.component.ts, I create an instance of it with the following child element: <app-parent> <h1>Hello</h1& ...

Is jQuery utilized by the bootstrap-grid system?

Finale: In our current setup, we are utilizing Angular 9, and like many frontend frameworks, there is a preference against incorporating other JavaScript libraries alongside the framework for manipulating the DOM. The Challenge: I am hesitant to include ...

Encountering an issue with Angular 5.2 application build on VSTS build server: Running into "CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory" error

Out of nowhere, the builds began failing with the following error : 2019-01-03T12:57:22.2223175Z EXEC : FATAL error : CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory error MSB3073: The command "node node_modules/webpack/bin/w ...