[英]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.