angular - 如何以角度动态添加表单控制组
问题描述
我是 Angular 新手,我正在根据我的要求使用表单控件添加一些字段。我需要动态添加一些包含数组的字段。但我不知道如何在 UI 中向用户展示这种功能。请帮助实现这一目标。这是示例 JSON
{
"city": "hyderabad",
"comboDesciption": "ioioioyio",
"label": "combo",
"price": 650,
"productIds": "Mutton Liver,Chicken",
"qtyIds": "500gm,700gm"
}
在上面的 JSON 中,我有 productIds,我需要为一个组合选择多个产品,并且它们各自的数量权重在 qtyIds 中引用。请建议我如何在数组中添加我的表单控制组来实现这一点
解决方案
我不确定我是否理解正确。
以下是在您的案例中如何使用反应式表单:
myForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.myForm = this.fb.group({
city: [null, Validators.required),
comboDescription: [null, Validators.required),
label: [null, Validators.required),
price: [null, [Validators.required, Validators.min(1)]),
productsIds: this.fb.array([], Validators.required),
qtyIds: this.fb.array([], Validators.required)
})
}
// create getters to retrieve the form array controls from the parent form group
public get productsIds(): FormArray {
return this.myForm.get('productsIds') as FormArray;
}
public get qtyIds(): FormArray {
return this.myForm.get('qtyIds') as FormArray;
}
// create methods for adding and removing productsIds
public addProduct(): void {
this.productsIds.push(this.fb.control('', [Validators.required]));
}
public removeProduct(index: number): void {
if(this.productsIds.length < 1) {
return;
}
this.productsIds.removeAt(index);
}
// do the same for the qtyIds
在模板中:
<form [formGroup]="myForm">
.
.
.
// example for productsIds
<div formArrayName="productsIds">
<button (click)="addProducts()">Add Product</button>
<div *ngFor="let productId of productsIds.controls; index as i">
<input type="text" [formControlName]="i">
<button (click)="removeProduct(i)">Remove Product</button>
</div>
</div>
.
.
.
</form>
推荐阅读
- android - Flutter:当键盘出现在android中时屏幕不会向上滚动
- google-chrome - 发送多个消息查询,但侦听器只接收一条消息
- python - 大数据中多列计算的内存错误
- swift - 将可解析的结构转换为可编码的结构不能按预期工作
- javascript - 我无法从 D3 中的 X 轴日期中删除逗号。已尝试 .format 和 timeParse 建议赞赏
- reactjs - 如何使用 React 更改输入字段的值?
- javascript - nuxt.config.js 没有加载 .css 文件
- sql - 在所有分区内搜索 - SQL
- python - Django collectstatic:是否可以访问 Django 项目之外的静态文件?
- php - 如何保存kartik可编辑yii2