Angular 单击一个复选框选择所有选项为什么?

Angular 单击一个复选框选择所有选项为什么?,angular,Angular,嗨,我正在设计具有多个值的checbox,但当我单击一个值时 复选框选择全部 {{initialInformationDetails.ObjectiveOfUsingServiceText} {{objective.value}} 使用[checked]代替[(ngModel)] {{initialInformationDetails.ObjectiveOfUsingServiceText} {{objective.value}} 既然您使用的是反应式表单,请使用它。不鼓励将ngModel与

嗨,我正在设计具有多个值的checbox,但当我单击一个值时 复选框选择全部


{{initialInformationDetails.ObjectiveOfUsingServiceText}
{{objective.value}}
使用[checked]代替[(ngModel)]


{{initialInformationDetails.ObjectiveOfUsingServiceText}
{{objective.value}}

既然您使用的是反应式表单,请使用它。不鼓励将
ngModel
与被动形式一起使用。在
ReactiveFormsModule
中,甚至不包括
ngModel
指令

由于有多个复选框,因此应使用
FormArray
来捕获值。我们可以将其称为FormArray
Objective of UsilingServiceControls

然后,我们有了一个方法,可以将项添加或删除到表单数组中。我们在模板中有一个更改事件,在该事件中,我们传递复选框的布尔值,这意味着它是否被选中,以及我们要添加到表单数组中的实际项目:

(change)="onChange(objective.value, $event.target.checked)"
onChange
方法如下所示:

onChange(值:string,isChecked:boolean){
让ObjectiveOfUsingServiceControls=
this.myForm.controls.objectiveOfUsingServiceControls;
如果(已检查){
push(新表单控件(值));
}否则{
let索引=
ObjectiveOfUsingServiceControls.controls.findIndex(x=>x.value==value)
使用ServiceControls.removeAt(索引)的目标;
}
}
如果我们将一个新的
FormControl
推送到表单数组中,或者如果未选中,则从表单数组中删除表单控件

由于您有一些预先检查的值,因此我们还需要在表单数组中首先添加该值。我们可以在构建表单后执行此操作,表单可以如下所示:(
fb
指的是
Formbuilder

ngOnInit(){
//构建形式
this.myForm=this.fb.group({
ObjectiveOfUsingServiceControls:this.fb.array([])
});
//迭代并检查哪个对象与“userInfo.objective”中的值匹配
for(让obj知道这个.initialInformationDetails.ObjectiveOfUsingService){
if(obj.value==this.userInfo.objective){
this.onChange(obj.value,true)
打破
}
}
}  
对于模板中的预检查值,只需使用
[checked]


{{objective.value}}

提交表单时,表单的所有值都在
myForm.value
中,只需将
myForm
更改为实际的表单名称即可。

但是我需要保存选中的数据以保存是否可以不使用[(ngModel)]查看此问题,它与您尝试的操作非常接近。你有反应形式吗?不鼓励将其与ngModel一起使用。我想知道formcontrolname,因为如果你想有几个复选框,它就不能与form控件一起工作,因为它只能捕获一个值,我想说你想要一个formarray。嘿,答案是怎么回事?是帮助了你还是需要进一步的帮助?:)
<div [ngClass] = "{'form-group': true}">
              <label>{{initialInformationDetails.objectiveOfUtilisingServiceText}}</label>
             <div>
                <label *ngFor = "let objective of initialInformationDetails.objectiveOfUtilisingService">
                <input type="checkbox" 
                       name="objective"
                       formControlName = "objectiveOfUtilisingServiceControl"
                       value="{{objective.value}}" 
                       [checked]="userInfo.objective"/> {{objective.value}}
                </label> 
         </div>
</div>
(change)="onChange(objective.value, $event.target.checked)"