0

I'm adding a form group dynamically to a form with FormArray. While I push a newly created form group and display in template, angular is having trouble to find the path of that control element.

I've referenced the angular doc on adding dynamic controls with form array. https://angular.io/guide/reactive-forms#dynamic-controls-using-form-arrays and also a similar problem in stack overflow : Angular: Cannot find control with path: 'variable-> 0 -> id'

component class:

get alternateAddress() {
    return this.signupForm.get('alternateAddress') as FormArray;
  }
 buildAddress() {
    return this.fb.group({
      city: [''],
      street: ['']
    });
  }
  addAlternateAddress() {
    this.alternateAddress.push( this.buildAddress());
  }
  ngOnInit() {
    this.signupForm = this.fb.group({
      name: ['', [Validators.required]],
      password: ['', [Validators.required]],
      confirmPassword: ['', [Validators.required]],
      email: ['', [Validators.email]],
      subscribe: [''],
      phone: ['', [Validators.required, Validators.pattern]],
      topic: ['', [Validators.required]],
      address: this.fb.group({
        city: [''],
        street: ['']
      }),
      alternateAddress: this.fb.array([ ])
    }, {validator: PasswordMatchValidator});

Component template

 <button type="button" class="btn btn-sm btn-warning" (click)="addAlternateAddress()">Add alternate address</button>
    <div *ngIf="alternateAddress.length > 0">
      <div class="form-group" formArrayName="alternateAddress" *ngFor="let addr of alternateAddress.controls; let i=index">
        <div [formGroupName]="alternateAddress.controls[i]">
          <div class="form-group">
            <label for="city">City</label>
            <input type="text" class="form-control" name="city" [formControlName]="city">
          </div>
          <div class="form-group">
            <label for="name">Street</label>
            <input type="text" class="form-control" name="street" [formControlName]="street">
          </div>
        </div>
      </div>
    </div>

I'm not quite sure how to provide a path to form group and refer to it's individual controls as in the documentation, only the controls part is demonstrated.

Thanks to the community for putting their effort to debug.

Debadatta Meher
  • 83
  • 2
  • 10

1 Answers1

0

Thanks developer033 for the comment. It indeed helped me to debug the code.

    <div class="form-group" formArrayName="alternateAddress" *ngFor="let addr of alternateAddress.controls; let i=index">
                <div [formGroupName]="i">
<div class="form-group">
                <label for="city">City</label>
                <input type="text" class="form-control" name="city" formControlName="city">
              </div>

This solved the issue. Binding the index to [formGroupName] and using the formControlName without square brackets.

Debadatta Meher
  • 83
  • 2
  • 10