如何在TypeScript中构建含默认未勾选复选框的表单函数?
Hey there! I see you're building a notification preferences form with checkboxes and want all of them to be unchecked by default. Let's tweak your buildForm() function to make that happen.
In Angular's reactive forms (which you're using with FormBuilder), checkboxes bind to boolean values—true for checked, false for unchecked. Right now your form controls are initialized with empty arrays [], which leaves their initial value as undefined. To explicitly set them to unchecked, we just need to pass false as the initial value for each control.
Here's the updated function:
buildForm(): void { console.log('build form'); this.notificationForm = this.fb.group({ appCreated: [false], appSubmittedReview: [false], appCancelReview: [false], appRequestForDeletion: [false], appDisable: [false], appReEnable: [false], appReviewPublished: [false], appReviewApproved: [false], appReviewDeleted: [false], }); }
Why this works:
When you define a form control with [false], you're setting its initial value to false—which corresponds to an unchecked checkbox. This is more reliable than leaving the initial value undefined, as it ensures the form control always has a boolean type value from the start, making it easier to work with when submitting or updating the form later.
If you ever need to pre-check some boxes in the future, just swap false with true for those specific fields.
内容的提问来源于stack exchange,提问作者Ilia Tapia

