[英]Angular 5 reactive form set mat-checkbox to check
我试图在Angular 5.1.2和Angular Material 5.0.2上使用mat-checkbox和反应形式。
一切都运行良好,除了当我使用patchValue({amateur:[false])时,它仍然被检查。 有什么奇怪的是我有其他形式,我在做同样的事情,他们工作正常。 它也不只是业余复选框,它是所有复选框都被选中。 仅以“业余”为例。
formControl amateur.value始终为false。 但是,一旦执行了修补值,就会检查控件。
我错过了什么?
HTML5
<form [formGroup]="showClassGrp">
<mat-checkbox id="amateur" class="amateur" color="primary"
formControlName="amateur">Amateur</mat-checkbox>
</form>
打字稿
FormBuilder的工作和显示是正确的。
this.showClassGrp = this.fb.group({
...
amateur: [false],
...
});
补丁showClassGrp和所有复选框都被检查,即使它们的formControl值为false。
this.showClassGrp.patchValue({
className: [this.showClass.className], //this works
amateur: [false], // this changed the display to checked.
...
});
如果您使用的是“响应”,则可能需要为表单中的每个成员分配一个FormControl。 像这样的东西
component.ts
showClassGrp: FormGroup;
constructor() { }
ngOnInit() {
this.showClassGrp = new FormGroup({
'amateur': new FormControl(false),
});
}
onSubmit(){
console.log(this.showClassGrp.value.amateur);
this.showClassGrp.patchValue({amateur: false});
console.log(this.showClassGrp.value.amateur);
}
component.html
<form [formGroup]="showClassGrp" (ngSubmit)="onSubmit()">
<mat-checkbox id="amateur" class="amateur" color="primary"
formControlName="amateur">Amateur</mat-checkbox>
<button class="btn btn-primary" type="submit"> Submit </button>
</form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.