【发布时间】:2019-04-06 02:51:19
【问题描述】:
这是我的表单组:
this.productGroup = this.fb.group({
name: ['', Validators.compose([Validators.required, Validators.maxLength(80)])],
desc: ['', Validators.maxLength(3000)],
category: ['', Validators.required]
variants: this.fb.array([
this.fb.group({
type: '',
options: ''
})
])
});
用户单击按钮后,我需要动态添加type 和options 控制字段。用户输入后 FormArray 应如下所示:
[ {type: 'size', options: 'Small', 'Big'}, {type: 'color', options: 'red', 'blue, 'yellow'}, ... ].
这是我想要做的:
// Add new item to FormArray
addItem(): void {
this.variantsArray = this.productGroup.get('variants') as FormArray;
this.variantsArray.push(this.fb.group({
type: '',
options: ''
}));
}
// Template
<form [formGroup]="productGroup">
// inputs...
<div formArrayName="variants" *ngFor="let item of productGroup.controls['variants']; let i = index;">
<div [formGroupName]="i">
<div class="row">
<mat-form-field class="col-12">
<input formControlName="type">
</mat-form-field>
</div>
<div class="row">
<mat-form-field class="col-12">
<input formControlName="options">
</mat-form-field>
</div>
</div>
<div class="row">
<a href="javascript:" (click)="addItem()"> Adicionar Variante </a>
<a href="javascript:" (click)="removeItem(i)" *ngIf="i > 0"> Remover Variante </a>
</div>
</div>
</form>
如何让它发挥作用?
【问题讨论】:
-
你怎么能像
{type: 'size', options: 'Small', 'Big'}显示的那样存储数据,这甚至不是像属性options: 'Small', 'Big'这样的有效javascript 对象。任何一个选项属性都应该是一个数组,否则你会得到长字符串 -
我将使用一个字符串数组将数据直接传递给我的组件上的这个 FormControl。更准确地说,我使用
MatChipInput将值传递给这个字符串数组。我正在尝试为输入获得一个通用的工作解决方案,以便我可以在我的代码上实现。
标签: javascript angular typescript angular-material angular-reactive-forms