0

I trying to use formArray but I got this error Cannot find control with path: 'nameDriver -> 1' I not sure where is my fault. This stackblitz demo code

HTML

<form [formGroup]="driverInfoForm">
<div class="row" formArrayName="nameDriver">
<div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 d-flex" [formGroupName]="i"
  *ngFor="let driver of nameDriver; let i=index">
  <label>{{i+1}}.Name</label>
  <input class="form-control" type="text" id="name" name="name{{i}}"  formControlName="name" [(ngModel)]="nameDriver[i].name"><br/>
  <label>{{i+1}}.Owner Id</label>
  <input class="form-control" type="text" id="ownerId" name="ownerId{{i}}" inputmode="numeric" dashFormat formControlName="ownerId" maxLength="14">
  <div class="col-2 col-sm-2 col-md-2 col-lg-2 col-xl-2" >
  <div class="form-group mb-0" *ngIf="i !== 0">
    
    <button class="btn btn-danger" (click)="removeDriver(i)">
      Delete
    </button>
  </div>
  <div class="form-group mb-2">
  
    <button *ngIf="i >= 0 && i < 1" type="button" [hidden]="nameDriver.length > 3" (click)="addDriver()" class="btn btn-primary">
      Add
    </button>
  </div>
</div>
</div>
</div>
</form>

Component

createDriver () {
    return new FormGroup({
      name: new FormControl(null, Validators.required),
      ownerId: new FormControl(null, Validators.required)
    })
  }

  // Add New Driver Handler
  addDriver() {
    this.nameDriver.push({
      name: '',
      ownerId: '',
    });
  }

  // Remove Driver Handler
  removeDriver(i: number) {

    if (i != 0) {
      this.nameDriver.splice(i, 1);
    } else {
      

    }

  }

1 Answer 1

1

You have at least to push somehow new FormGroup into the FormArray.

// Add New Driver Handler
addDriver() {
  // push new driver control    
  (this.driverInfoForm.get('nameDriver') as FormArray).push( this.createDriver() );
  this.nameDriver.push({
    name: '',
    ownerId: '',
   });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.