angular如何动态添加组件列表
angular how to dynamically add a list of components
所以基本上我有一个按钮,让我可以选择添加一个包含 2 个输入的组件。他们的用户可以多次添加这个组件。但我试过 ComponentFactoryResolver
但它一次只能添加一个组件。
当我按下添加合同时,我将添加一个包含输入字段和标签的卡片组件
使用 *ngFor
循环模型,然后显示 child
根据您想要实现的功能,您需要像已经提到的评论中那样,在 TS 文件中建立模型,该模型将在 HTML 模板中循环使用 *ngFor
。将此与 child 组件结合使用,您可以轻松添加这些组件,例如单击按钮
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">
- 要指定 child 组件,您可以使用
@Input()
装饰器。例如,如果您想要显示不同的形式或不同的元素,您可以将 input
中的数据传递给 child。
所以基本上我有一个按钮,让我可以选择添加一个包含 2 个输入的组件。他们的用户可以多次添加这个组件。但我试过 ComponentFactoryResolver
但它一次只能添加一个组件。
当我按下添加合同时,我将添加一个包含输入字段和标签的卡片组件
使用 *ngFor
循环模型,然后显示 child
根据您想要实现的功能,您需要像已经提到的评论中那样,在 TS 文件中建立模型,该模型将在 HTML 模板中循环使用 *ngFor
。将此与 child 组件结合使用,您可以轻松添加这些组件,例如单击按钮
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">
- 要指定 child 组件,您可以使用
@Input()
装饰器。例如,如果您想要显示不同的形式或不同的元素,您可以将input
中的数据传递给 child。