动态复选框未加载

时间:2017-02-05 11:56:36

标签: angular typescript checkbox formbuilder

我有一组从业务单元加载的“业务单位”复选框,我想在其上执行验证。

正如我所设置的那样,即使值已成功从db返回,它们也不会显示。

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

formgroup在构造函数

中初始化
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>

为什么值不显示? 我怎样才能纠正这个问题?

由于

2 个答案:

答案 0 :(得分:1)

问题是构造函数是在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;
    })

答案 1 :(得分:0)

AFAIK引用数组项的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'将用作名称而不是索引。