简体   繁体   中英

Angular 8 dynamic checkbox and dropdown from data from api

Here is my stack blitz https://stackblitz.com/edit/angular-w8g8ng?file=src%2Fapp%2Fapp.component.html

I want to hide the dropdownif the divisions are empty and also default the value of the dropdown to the first one. How can i do this? Please help.

<form [formGroup]='newEmployeeForm' class="w-60-l">
  <label [for]="i"  formArrayName="planDivList"
          *ngFor="let plan of newEmployeeForm.controls.planDivList.controls; let i = index"><br>

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

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

        </label>

        <div
          *ngIf="formInvalid && newEmployeeForm.controls.planDivList.hasError('required')">
        At least one plan must be selected
        </div>
</form>

Here is my dataset from api that keeps changing

 planDivList = [
    { 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" }] }

  ];    

To hide the dropdown you need to add the *ngIf in the select tag, like this:

<select *ngIf="planDivList[i].divisions.length > 0" id="inputDiv"...

And to select the first value of dropdown, you set the value of formControl when you create it, like:

divCtrl: new FormControl(this.planDivList[0].divisions[0], [Validators.required])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM