当mat-checkbox
属性设置为true时,不会默认检查checked
:
<mat-checkbox value="true" formControlName="updates" checked="true">Get Updates</mat-checkbox>
不使用已检查。如果您使用了Reactive Forms,则只需为该字段设置一个值
//When you create the form
this.form=new FormGroup({
updates:new FormControl(true)
}
//Or in a function
this.form.get('updates').setValue(true)
<!--no value, no checked, just formControlName-->
<form [formGroup]="form">
<mat-checkbox formControlName="updates" >Get Updates</mat-checkbox>
</form>
使用双向绑定。
<mat-checkbox value="true" formControlName="updates" [checked]="true">Get Updates</mat-checkbox>
就Reactive表单而言,我还没有找到一种动态检查复选框并更新表单控件值的方法。
使用[checked]
只检查HTML复选框元素,但不影响控件。
如果必须根据变量的值动态处理复选框,则可以使用此方法。
具有决定已检查状态的变量的setter和getter,更新setter中的表单控件。
就像是:
private _checkBoxChecked = false
set checkBoxChecked(val) {
this._checkBoxChecked = val
this.form.get('con').setValue(this.checkBoxChecked); // update your checbox control here
}
get checkBoxChecked() {
return this._checkBoxChecked
}
ngOnInit() {
this.form = this._fb.group({
con: [this.checkBoxChecked]
})
}
在这里查看示例:https://stackblitz.com/edit/angular-hba5pt?file=src%2Fapp%2Fapp.component.ts
在添加的示例中,它是普通输入复选框,而不是mat-input复选框,但理想情况下,此方法也适用于此。