问题描述
我需要将输入字段添加到对象数组和一个根据用户选择动态增长的地图.
I need to add input fields to array of objects and a map which grows dynamically based on user's choice.
例如 InputForm
有一个列表和一个地图,需要用户填写.
For e.g. InputForm
has a list and a map which needs to be filled by user.
export class InputForm {
mapA: {};
listA: ListA[] = [];
}
export class ListA {
input1 : String
input2 : number
}
我需要以这样的方式在UI上显示它:标准映射的input1,input2和key,值可以作为输入字段可见.用户填写所有4个输入字段,然后单击添加"按钮.
I need to show it on UI in such a way that input1, input2 and key, value for map of criteria is visible as the input field. The user fills all 4 input fields and clicks on the add button.
然后,对于第二个输入,相同的输入字段应再次为用户可编辑.这样,他就可以构建列表和地图,并且当他单击提交"按钮数组和地图时,应该已经填充了所有值.
Then again same input fields should be editable for the user for the second input. This way he can build list and map and when he clicks on submit button array and map should have all the values filled before.
* ngFor
不起作用,因为初始列表为空.
*ngFor
doesn't work because the initial list is empty.
推荐答案
假定您使用的是 Angular反应形式,您可以结合使用 * ngFor
和 FormArray
.您可以从一个空的 FormArray
开始,然后使用 .push()
方法动态添加.
Assuming you are using Angular Reactive Form, you can use a combination of *ngFor
and FormArray
. You can start with an empty FormArray
and add dynamically using the .push()
method.
这是一个好的详细示例
// order-form.component.ts:
@Component({
selector: '...',
templateUrl: './order-form.component.html'
})
export class OrderFormComponent implements OnInit{
orderForm: FormGroup;
items: FormArray;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.orderForm = this.formBuilder.group({
customerName: '',
email: '',
items: this.formBuilder.array([ this.createItem() ])
});
}
createItem(): FormGroup {
return this.formBuilder.group({
name: '',
description: '',
price: ''
});
}
addItem(): void {
this.items = this.orderForm.get('items') as FormArray;
this.items.push(this.createItem());
}
}
<!-- order-form.component.html -->
<div formArrayName="items"
*ngFor="let item of orderForm.get('items').controls; let i = index;">
<div [formGroupName]="i">
<input formControlName="name" placeholder="Item name">
<input formControlName="description" placeholder="Item description">
<input formControlName="price" placeholder="Item price">
</div>
Chosen name: {{ orderForm.controls.items.controls[i].controls.name.value }}
</div>
这篇关于如何在角度6中动态添加输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!