简体   繁体   English

angular 如何动态添加组件列表

[英]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 .所以基本上我有一个按钮,让我可以选择添加一个包含 2 个输入的组件。 and they user can add this component multiple times .他们用户可以多次添加这个组件。 but i tried ComponentFactoryResolver but it can only add one component at the time .但我尝试了ComponentFactoryResolver但它当时只能添加一个组件。 在此处输入图片说明

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使用*ngFor遍历一个模型,然后显示孩子

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 .根据您想要实现的功能,您需要在已经提到的注释中,在 TS 文件中创建模型,该文件将在 HTML 模板中使用*ngFor Using this in combination with child components you can add those easily with for example a button click将此与子组件结合使用,您可以轻松添加这些组件,例如单击按钮

TS Parent TS 父母

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 HTML 父级

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

HTML Child HTML 子级

<p> Input: </p>
<input type="text">
  • To specify your child component you can use @Input() decorator.要指定您的子组件,您可以使用@Input()装饰器。 There you can pass the data in input to the child if you want for example show different forms or different elements.如果您想显示不同的表单或不同的元素,您可以在那里将input的数据传递给孩子。

For your refernce: https://stackblitz.com/edit/angular-hrdtcu供您参考: https ://stackblitz.com/edit/angular-hrdtcu

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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