Search code examples
angularselectangular-uicheckboxlist

Build dynamic fields in Angular 8


I have an array that looks like this ( this is data from api that will keep changing.. this is just sample)

planDivList = [
    { planCode: "A", divisions: [] },
    { planCode: "B", divisions: [] },
    { planCode: "C", divisions: [{ divisionCode: "2", divisionName: "Assisted Living " }, { divisionCode: "1", divisionName: "LILC" }] },
    { planCode: "D", divisions: [{ divisionCode: "3", divisionName: "Four Seasons" }, { divisionCode: "2", divisionName: "Lakeside" }, { divisionCode: "1", divisionName: "Sunrise" }] }
  ];

i need to dynamicallly build check boxes for planCode and divisions as dropdown for each checkbox..

my html:

<div class="form-check"> 
      <label [for]="i" class="form-check-label fw7 h5 mb0" formArrayName="planDivList"
          *ngFor="let plan of newEmployeeForm.controls.planDivList.controls; let i = index"><br>

          <input [name]="i" [id]="i" class="form-check-input" type="checkbox" [formControlName]="i">
          {{planDivList[i].planCode}}

          <label for="inputDiv">Divsions
        <div>
          <select id="inputDiv" [(ngModel)]="division" (ngModelChange)="errMsg = ''"
            [ngModelOptions]="{standalone: true}" formcontrolName='divCtrl'>
            <option selected>Choose...</option>
            <option *ngFor="let division of planDivList[i].divisions">{{division.divisionsName}}</option>
          </select>
        </div>


 </label>
        </label>


        <div class="error-message nt3 mb3 white flex items-center fw7"
         *ngIf="formInvalid && newEmployeeForm.controls.planDivList.hasError('required')">
         <i class="icon-alert s15 mr2"></i>At least one plan must be selected
        </div>

      </div>

I am able to build the plans but not the divsions as dropdwn.I am not sure how to build the dropdowns for each plancode. Please help i am new to Angular.


Solution

  • I think the problem lies in your option's *ngFor. Try this:

    <option *ngFor="let division of planDivList[i].divisions">{{division.divisionsName}}</option>
    

    You are already inside a loop of "newEmployeeForm.controls.planDivList.controls" - so looping again is unnecessary, and i think where the problem is.