如何动态创建多个输入,然后在Angular 2中获取它们的值?
我用的是Angular 2 我想动态创建多个输入,然后通过使用如何动态创建多个输入,然后在Angular 2中获取它们的值?,angular,Angular,我用的是Angular 2 我想动态创建多个输入,然后通过使用[(ngModel)]=“input1”或其他方式提供获取其值的方法: 我曾考虑过使用[hidden],但由于我不知道用户需要输入的确切数量,所以我询问了如何动态创建输入 html <button (click)="addInput()">Add Input</button> 添加输入 ts addInput() { // first time click, add <input type="
[(ngModel)]=“input1”
或其他方式提供获取其值的方法:
我曾考虑过使用[hidden]
,但由于我不知道用户需要输入的确切数量,所以我询问了如何动态创建输入
html
<button (click)="addInput()">Add Input</button>
添加输入
ts
addInput() {
// first time click, add <input type="text" [(ngModel)]="input1"/>
// second time click, add <input type="text" [(ngModel)]="input2"/>
// third time click, add <input type="text" [(ngModel)]="input3"/>
// forth, fifth, etc.
}
addInput(){
//首次单击“添加”
//再次单击“添加”
//第三次单击“添加”
//第四、第五等。
}
谢谢您可以在表单对象上使用addControl:
this.yourForm.addControl("inputName", new Control);
创建一个对象数组。当需要新的输入时,将其推到阵列上。使用
NgFor
生成表单元素
@Component({
selector: 'my-app',
template: `<button (click)="addInput()">Add Input</button>
<div *ngFor="let input of inputs">
<input [(ngModel)]="input.value">
</div>
{{inputs | json}}`
})
export class AppComponent {
inputs = [{value: "first"}];
addInput() {
this.inputs.push({value: ''});
}
}
@组件({
选择器:“我的应用程序”,
模板:`添加输入
{{输入| json}`
})
导出类AppComponent{
输入=[{value:“first”}];
addInput(){
this.inputs.push({value:'});
}
}
这很有效。但是,我希望使用相同的方法创建选择/选项设置。可能吗?我从不同的角度尝试,但只得到了一堆关于“未指定名称属性的表单控件的无值访问器”的巨大错误。。。