要解决Angular响应式表单多选框在第二次访问时即使某些值为false仍然显示为选中状态的问题,可以按照以下步骤进行修改:
在组件的初始化方法中,为表单控件设置初始值。这可以通过使用setValue
或patchValue
方法来完成。
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.scss']
})
export class YourComponent implements OnInit {
form: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.form = this.fb.group({
checkbox1: false,
checkbox2: false,
checkbox3: false
});
// 设置初始值
this.form.patchValue({
checkbox1: false,
checkbox2: false,
checkbox3: false
});
}
}
在模板中,使用formControlName
指令将表单控件与多选框相关联,并使用[checked]
属性来确定是否应该选中。
通过使用form.get('checkbox1').value
表达式,我们可以获取表单控件的当前值,并将其传递给[checked]
属性来确定多选框是否应该选中。
这样,即使在第二次访问页面时,如果某些值为false,多选框也将正确地显示为未选中状态。