I'm trying to create a dynamic form group where user can see the list of items (if loading from server for example) and so the user pushes controls to the array, but I'm having issues displaying and doing so.
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);
}
These are the errors I'm getting:
TypeError: Cannot read properties of null (reading 'controls')
TypeError: Cannot read properties of null (reading 'push')