动态复选框未加载

Dynamic checkboxes not loading

我从数据库中加载了一组 'business units' 的复选框,我想对其执行验证。

正如我现在设置的那样,即使值 return 从数据库中成功获得,它们也没有显示。

ngOnInit() {
    this.commServe.getBusinessUnitsOnly().subscribe((data) => {
        this.businessUnits = data;
    },
        (error) => {
            this.errorMessage = <any>error;
        })
}

表单组在构造函数中初始化

this.registrationForm = fb.group({

        "firstName": new FormControl('', [Validators.required]),
        "lastName": new FormControl('', [Validators.required]),
        "password": new FormControl('', [Validators.required]),
        "confirmPassword": new FormControl('', [Validators.required]),
        bUnits: this.fb.array(
            this.businessUnits.map(() => this.fb.control('')),
            CustomValidators.multipleCheckboxRequireOne
        )

    })

这是标记

 <div formArrayName="bUnits">
    <div class="checkbox"*ngFor="let unit of registrationForm.controls.bUnits.controls; let i = index;">
      <label><input type="checkbox" #instance  formControlName="i" (click)="getCheckBoxValue(instance.checked, businessUnits[i].BuName)">{{ businessUnits[i].BuName}}</label>
    </div>
  </div>

为什么不显示值? 我该如何纠正这个问题?

谢谢

据我所知,引用数组项的 formControlName 应该只是索引:

  <label><input type="checkbox" #instance  [formControlName]="i" (click)="getCheckBoxValue(instance.checked, businessUnits[i].BuName)">{{ businessUnits[i].BuName}}</label>

另见 https://angular.io/docs/ts/latest/guide/reactive-forms.html#!#form-array

Plunker example

formControlName="i"

应该是

[formControlName]="i"

否则字符串 'i' 将用作名称而不是索引。

问题是在 ngOnInit 之前调用了构造函数。这意味着您的表单在数据加载之前创建。因为你没有说任何错误,我怀疑你正在将 businessUnits 初始化为一个空数组。

解决问题的一种方法是将初始化逻辑移至订阅。这将确保加载数据:

this.commServe.getBusinessUnitsOnly().subscribe((data) => {
    this.businessUnits = data;
    this.registrationForm
        .setControl("bUnits", this.fb.array(
            this.businessUnits.map(() => this.fb.control('')),
            CustomValidators.multipleCheckboxRequireOne))
},
    (error) => {
        this.errorMessage = <any>error;
    })