【发布时间】:2022-01-12 08:07:07
【问题描述】:
我正在尝试创建一个动态表单组,用户可以在其中看到项目列表(例如,如果从服务器加载),因此用户将控件推送到数组,但我在显示和这样做时遇到问题。
HTML:
<ng-container formArrayName="additionalId">
<div class="form-group mb-2" *ngFor="let _ of additionalId.controls; index as i">
<label for="additionalId{{ i }}">Additional ID</label>
<ng-container [formGroupName]="i">
<input type="text" class="form-control" id="additionalId{{ i }}" [formControlName]="i">
</ng-container>
</div>
</ng-container>
JS:
addVehicle = new FormGroup({
uid: new FormControl(),
identifier: new FormControl(),
defaultDriver: new FormControl(),
defaultRoute: new FormControl(),
defaultYard: new FormControl(),
defaultDriverId: new FormControl(),
defaultRouteId: new FormControl(),
defaultYardId: new FormControl(),
vehicle: new FormGroup({
year: new FormControl(),
make: new FormControl(),
model: new FormControl(),
seatCount: new FormControl(),
length: new FormControl(),
number: new FormControl('', Validators.required),
maintId: new FormControl(),
vin: new FormControl(),
license: new FormControl(),
additionalId: new FormArray([
new FormGroup({
label: new FormControl('test'),
number: new FormControl('123')
})
]),
transit: new FormArray([
new FormGroup({
label: new FormControl(''),
number: new FormControl('')
})
]),
metadata: new FormArray([
new FormGroup({
label: new FormControl(''),
number: new FormControl('')
})
])
})
})
ngOnInit(): void {
this.additionalId = this.addVehicle.get('additionalId') as FormArray
}
submit() {
console.log(this.addVehicle)
let control = new FormControl('', Validators.required);
this.additionalId.push(control);
}
这些是我得到的错误:
TypeError:无法读取 null 的属性(读取“控件”)
TypeError: Cannot read properties of null (reading 'push')
【问题讨论】:
标签: angular typescript