Reputation: 9043
I have a group of checkboxes of 'business units' loaded from the database upon which I want to perform validation.
As I have it setup at the moment they are not displaying even though the values did return from the db successfully.
ngOnInit() {
this.commServe.getBusinessUnitsOnly().subscribe((data) => {
this.businessUnits = data;
},
(error) => {
this.errorMessage = <any>error;
})
}
the formgroup is initialized in the constructor
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
)
})
this is the markup
<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>
Why are the values not displaying? How can I go about in rectifying this?
Thanks
Upvotes: 1
Views: 50
Reputation: 657118
AFAIK the formControlName
that references an array item should just be the index:
<label><input type="checkbox" #instance [formControlName]="i" (click)="getCheckBoxValue(instance.checked, businessUnits[i].BuName)">{{ businessUnits[i].BuName}}</label>
See also https://angular.io/docs/ts/latest/guide/reactive-forms.html#!#form-array
formControlName="i"
should be
[formControlName]="i"
otherwise the string 'i'
will be used as name instead of the index.
Upvotes: 0
Reputation: 14201
The issue is that the constructor is called before ngOnInit
. This means that your form gets created before your data loads. Since you didn't say anything about an error I suspect that you are initializing businessUnits
to be an empty Array.
One way to fix your issue is to move your initialization logic to the subscribe. This will ensure that the data is loaded:
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;
})
Upvotes: 1