Within my JavaScript model, this.profile
, there exists a property named emails
. This property is an array composed of objects with the properties {email, isDefault, status}
.
Following this, I proceed to define it as shown below:
this.profileForm = this.formBuilder.group({
.... other properties here
emails: [this.profile.emails]
});
console.log(this.profile.emails); //is an array
console.log(this.profileForm.emails); // undefined
In the HTML file, I utilize it in the following manner:
<div *ngFor="let emailInfo of profileForm.emails">
{{emailInfo.email}}
<button (click)="removeEmail(emailInfo)">
Remove
</button>
</div>
If I opt not to include it within the formGroup
and use it purely as an array - as depicted below - everything works perfectly. However, I have a business requirement that dictates this array must not be empty, which complicates setting form validation based on the length.
emails : [];
this.profileForm = this.formBuilder.group({
.... other properties here
});
this.emails = this.profile.emails;
console.log(this.profile.emails); //is an array
console.log(this.emails); // is an array
I also attempted utilizing formBuilder.array
, but soon realized it's intended for arrays of controls rather than data arrays.
emails: this.formBuilder.array([this.profile.emails])
Thus, my primary inquiry involves how best to bind an array from the model to the UI and how to effectively validate the array's length?