Angular14编辑表单中布尔值复选框无法正确回显的解决方法
问题描述
在Angular 14项目中,我定义了包含boolean类型isAdmin字段的IStudentUpdate接口,编写组件逻辑和模板后,加载编辑表单时其他字段均能正常显示数据,但isAdmin对应的复选框无法根据布尔值自动勾选,请问如何修正该问题?
接口定义
export interface IStudentUpdate { id: string; firstName: string; lastName: string; userName: string; email: string; mobileNumber: string; isAdmin: boolean; }
组件逻辑(component.ts)
editStudent() { this.editStudentForm = this.fb.group({ firstName: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(25), Validators.pattern('^[a-zA-Z \-\']+')]], lastName: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(25), Validators.pattern('^[a-zA-Z \-\']+')]], userName: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(50), UsernameValidator.cannotContainSpace]], email: ['', [Validators.required, Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$')]], mobileNumber: ['', [Validators.maxLength(15)]], isAdmin: [''] }); } editStudentData(templateDetail: TemplateRef<any>, row: any) { this.studentList = row this.editStudentForm.controls['firstName'].setValue(row.firstName); this.editStudentForm.controls['lastName'].setValue(row.lastName); this.editStudentForm.controls['userName'].setValue(row.userName); this.editStudentForm.controls['email'].setValue(row.email); this.editStudentForm.controls['mobileNumber'].setValue(row.mobileNumber); this.editStudentForm.controls['isAdmin'].setValue(row.isAdmin.value); this.bsModalRef = this.modalService.show(templateDetail, Object.assign({}, { class: 'gray modal-lg' })); }
组件模板(component.html)
<ng-template #studentEdit> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title pull-left">{{ pageLabel }}</h4> <button type="button" class="btn-close close pull-right" aria-label="Close" (click)="onClose()"> <span aria-hidden="true" class="visually-hidden">×</span> </button> </div> <form class="form-horizontal" id="add-form" [formGroup]="editStudentForm" (ngSubmit)="onEditStudentSubmitForm()"> <div class="modal-body"> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label for="firstName">First Name<span style="color:red;">*</span></label> <input type="text" class="form-control" formControlName='firstName' id="firstName" placeholder="First Name"> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="lastName">Last Name<span style="color:red;">*</span></label> <input type="text" class="form-control" formControlName='lastName' id="lastName" placeholder="Last Name"> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="userName">User Name<span style="color:red;">*</span></label> <input type="text" class="form-control" formControlName='userName' id="username" placeholder="Username"> </div> </div> </div> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label for="Email">Email<span style="color:red;">*</span></label> <input type="email" class="form-control" formControlName='email' id="studentEmail" placeholder="example@email.com"> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="mobileNumber">Mobile Number</label> <ngx-intl-tel-input [cssClass]="'form-control mb-3'" [preferredCountries]="preferredCountries" [enableAutoCountrySelect]="false" [enablePlaceholder]="true" [searchCountryFlag]="true" [searchCountryField]="[SearchCountryField.Iso2, SearchCountryField.Name]" [selectFirstCountry]="false" [selectedCountryISO]="CountryISO.Nigeria" [phoneValidation]="true" [separateDialCode]="true" name="mobileNumber" formControlName="mobileNumber"> </ngx-intl-tel-input> </div> </div> <div class="col-md-4"> <div class="form-group"> <div class="custom-control custom-checkbox"><br><br> <input class="custom-control-input" type="checkbox" id="isAdmin"> <label for="isAdmin" class="custom-control-label">Is Admin</label> </div> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" id="cancelCreate" class="btn btn-secondary" data-dismiss="modal" (click)="onClose()">Close</button> <button type="submit" class="btn btn-success" [disabled]="isLoading" (click)="editValidate()"><span *ngIf="isLoading" class="spinner-border spinner-border-sm mr-1"></span> <i class="fa fa-save" aria-hidden="true"></i> Save Changes</button> </div> </form> </div> </ng-template>
修正方案
复选框无法自动勾选是三个细节错误导致的,逐一修正即可:
1. 修正表单控件初始化类型
isAdmin是布尔类型,表单初始化时不能用空字符串作为默认值,改为布尔值:
// 在editStudent方法中修改isAdmin的初始化 isAdmin: [false] // 默认未勾选,若需要默认勾选则设为true
2. 修正赋值逻辑
接口中isAdmin本身就是布尔值,不需要额外访问.value属性,直接赋值即可:
// 在editStudentData方法中修改isAdmin的赋值 this.editStudentForm.controls['isAdmin'].setValue(row.isAdmin);
3. 模板中绑定表单控件
复选框未关联表单控件,添加formControlName属性:
<input class="custom-control-input" type="checkbox" id="isAdmin" formControlName="isAdmin">
内容的提问来源于stack exchange,提问作者Ayobamilaye
相关产品推荐
相关产品推荐

