实际上,在添加单击时,我需要添加行,但我无法获取 ngmodel 对象,或者是否有其他最佳方法来使用响应式(Reactive)表单来实现,所以最后的要求是在添加单击时获取一行并获取表单值的最佳实现方式或者请修改上面的代码
最佳答案
在此处查看现场演示。
http://keepnote.cc/code/form-group-with-formarray-adding-dyamic-row-angular-5-6
请检查一下。
我们必须使用 FormBuilder
和 FormBuilder.array
来处理动态行。
html
<form [formGroup]="carForm" (ngSubmit)="saveIntergration()">
<div formArrayName="details" class="form-group" *ngFor="let field of carForm.get('details').controls; let ind = index;">
<div [formGroupName]="ind">
Type:
<input type="text" formControlName="type">
model:
<input type="text" formControlName="model">
year:
<input type="text" formControlName="year">
make:
<input type="text" formControlName="make">
color
<input type="text" formControlName="color">
plateNumber
<input type="text" formControlName="plateNumber">
<hr>
</div>
</div>
</form>
<button (click)="addRow()">Add New</button>
<pre>
{{carForm.value | json}}
</pre>
ts
import { Component, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators, FormArray } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
public carForm: FormGroup;
constructor(private fb: FormBuilder) {
const items = [];
items.push(this.fb.group({
type: [],
model: [],
year: [],
make: [],
color: [],
plateNumber: []
}));
this.carForm = this.fb.group({
details: this.fb.array( items )
});
}
addRow() {
const details = this.carForm.get('details') as FormArray;
details.push(this.createItem());
}
createItem(): FormGroup {
return this.fb.group({
type: [],
model: [],
year: [],
make: [],
color: [],
plateNumber: []
});
}
}
关于angular - 单击添加按钮将行添加到表中,新行是每个单元格中的表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53513269/