Cannot find control with path: 'plans -> 0'

Margerine

I have an API that returns the data something like but the class is same but number of entries changes.

HTML file:

<div class="col-12 col-md-6" formArrayName="plans">
  <div class="form-check" 
      *ngFor="let plan of plans; index as i" [formGroupName]="i">
    <label class="form-check-label fw7 h5 mb0">
      <input class="form-check-input" type="checkbox" formControlName="checkbox">
      {{plan.planCode}}
    </label>

    <label *ngIf="plan.divisions.length > 0">
      Divisions
      <select class="form-control" formControlName="division">
        <option *ngFor="let division of plan.divisions" [value]="division.divisionCode">
          {{division.divisionName}}
        </option>
      </select>
    </label>
  </div>         
</div>

TS file:

public plans: IPlan[] = new Array<Plan>();
public formControls: {
  firstNameCtrl: FormControl,    
  plans: {
    checkbox: FormControl;
    division: FormControl;
  }[]
};

ngOnInit() {
  this.restSvc.getData("/api/plan/GetPlanDetails")
    .subscribe((data => {
      if (!data.errorMessage) {
        this.plans = data;          
      } else {
        this.errMsg = data.errorMessage;
      }
    }), error => {
      this.errMsg = "We found some errors. Please review the form and make corrections.";
  });

  this.formControls = {
    firstNameCtrl: this.fb.control('', Validators.required),   
    plans: this.plans.map((plan, i) => {
      const divisionCode = plan.divisions.length > 0
        ? plan.divisions[0].divisionCode
        : '';
      return {
        checkbox: this.fb.control(i === 0),
        division: this.fb.control(divisionCode)
      };
    })
  };
}

I am getting error

Cannot find control with path: 'plans -> 0'

where the plan is getting mapped before the subscribe completes. How to resolve this?

Sample data:

plans = [ 
  { planCode: "B3692", divisions: [] }, 
  { planCode: "B3693", divisions: [] }, 
  { planCode: "B67", 
    divisions: [ 
      { divisionCode: "2", divisionName: "Assisted Living " }, 
      { divisionCode: "1", divisionName: "LILC" }] 
  }, 
  { planCode: "B69", 
    divisions: [ 
      { divisionCode: "3", divisionName: "Four Seasons" }, 
      { divisionCode: "2", divisionName: "Lakeside" }, 
      { divisionCode: "1", divisionName: "Sunrise" } ] 
  } 
];
Kurt Hamilton

You need to build your form after your service returns the data.

Think of your ngOnInit function in steps.

  1. Request data
  2. Build form
  3. Build form array from empty plans array
  4. HTML is built

...

  1. Service returns data
  2. Update plans array
  3. HTML is updated

You now have a situation where *ngFor="let plan of plans" is creating a block of HTML for each plan, but you haven't added any form controls to your form.plans array. So when the form tries to bind to the first form control in form.plans, it doesn't find anything and breaks.

How to solve this?

The ultimate problem here is that your form array always needs to mirror the model you are building it from, otherwise the difference in array lengths is going to cause problems.

As far as I can tell, there isn't much point in you displaying a partial form while waiting for the service to return the plans. So I would recommend delaying the building of the form until you have all of the data. You would do this by building the form from inside the subscribe.

// no point in initialising with an empty array
plans: IPlan[];
formControls: {
  firstNameCtrl: FormControl,    
  plans: {
    checkbox: FormControl;
    division: FormControl;
  }[]
};

ngOnInit() {
  this.restSvc.getData("/api/plan/GetPlanDetails").subscribe(plans => {
    if (!plans.errorMessage) {
      this.plans = plans;
      this.buildForm();
    } else {
      this.errMsg = plans.errorMessage;
    }
  }, error => {
    this.errMsg = "We found some errors. Please review the form and make corrections.";
  });  
}

private buildForm(): void {
  this.formControls = {
    firstNameCtrl: this.fb.control('', Validators.required),   
    plans: this.plans.map((plan, i) => {
      const divisionCode = plan.divisions.length > 0
        ? plan.divisions[0].divisionCode
        : '';
      return {
        checkbox: this.fb.control(i === 0),
        division: this.fb.control(divisionCode)
      };
    })
  };

  // TODO: build the form here
}

You will now need to control when your form is added to the DOM, as you won't have a form for it to bind to when it is initially built.

<form *ngIf="form" [formGroup]="form">
  <!-- the form -->
</form>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Cannot find control with path: 'members -> 0 ->

Angular 5 FormArray > Cannot find control with path: 'fields -> 0 -> name'

Angular: Cannot find control with path: 'variable-> 0 -> id'

Angular Error As Cannot find control with path: '_OSkilss -> 0 -> Imageuploade'

Get error: Cannot find control with path: 'excludedPeriods -> 0 -> dateTo'

Get the following error : Error: Cannot find control with path: 'budgetIncomes -> 0 -> '

Error:Cannot find control with path: 'users -> 0 -> data -> cat_name

Angular. FormArray. Cannot find control with path: 'jobs -> 0 -> name'

Nested Form Array Woes: ERROR Error: Cannot find control with path: 'questions -> 0 -> code'

Angular Form Array Cannot find control with path

Angular 2 Form "Cannot find control with path"

Angular Reactive Forms: Cannot find control with path:

Cannot find control with path: 'marketplace -> 1 -> marketplace'

Angular FormArray: Cannot find control with path

ERROR Error: Cannot find control with path

Cannot find control with path 'myFormArray -> [index] -> myProperty

Cannot find control with path: 'data -> 1 -> value'

Angular formArray Cannot find control with path

"Cannot find control with path" but cannot figure out why - Angular 5

Angular 2 Reactive Forms: Cannot find control with path

angular 4: nested form fields : Cannot find control with path

Angular 7 and form arrays error of cannot find a control with path

Angular 8 and form arrays error cannot find control with path: index

Error: Cannot find control with path: 'specs -> 2' FormArray checkbox list

Error: Cannot find control with path: 'x ' angular 2

ERROR Error: Cannot find control with path: 'flights -> 3'

Cannot Find Control with Path Using ngIf on Recursive Angular Form

Form Array: Cannot find control with path: 'list -> description'

ERROR Error: Cannot find control with path: Angular FormArray

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive