简体   繁体   English

Angular 8 动态复选框和来自 api 数据的下拉列表

[英]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这是我的堆栈闪电战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这是我来自 api 的数据集,它不断变化

 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:要隐藏下拉列表,您需要在选择标签中添加 *ngIf,如下所示:

<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:要选择下拉列表的第一个值,请在创建时设置 formControl 的值,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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