0

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')

1 Answer 1

0

additionalId lives in the vehicle FormGroup.

access it via the vehicle FormGroup.

this.addVehicle.get('vehicle').get('additionalId') ...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.