简体   繁体   中英

angular how to dynamically add a list of components

So basically i have a button that give me the choice to add a component that contains 2 inputs . and they user can add this component multiple times . but i tried ComponentFactoryResolver but it can only add one component at the time . 在此处输入图片说明

when i press add contract i will a component who is a card that contains an input fields and label

Use *ngFor to loop through a model which then shows the child

Given from the feature you want to achive, you need as in the comments already mentioned, model in the TS file which will be looped through in the HTML template with an *ngFor . Using this in combination with child components you can add those easily with for example a button click

TS Parent

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  // specifies the input data
  inputs = []

  addInput() {
    // Here you can specify the data
    this.inputs.push({});
  }
}

HTML Parent

<button (click)="addInput()">Add Input</button>
<app-child *ngFor="let input of inputs"></app-child>

HTML Child

<p> Input: </p>
<input type="text">
  • To specify your child component you can use @Input() decorator. There you can pass the data in input to the child if you want for example show different forms or different elements.

For your refernce: https://stackblitz.com/edit/angular-hrdtcu

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM