首页 > 解决方案 > 如何从角度材料复选框中获取 0 值

问题描述

我是 angular 的 biginner,我在我的表单 mat-checkbox 中使用:

 <mat-card-content [formGroup]="formGroupContent">
    <section>
             <mat-checkbox formControlName="confirmcheck" [checked]="false">admin confirm 
             </mat-checkbox>
    </section>
 </mat-card-content>

在 ts 文件中:

ngOnInit(): void {
        this.formGroupContent = this.formBuilder.group({
        confirmcheck:new FormControl('')
        });

const chk=this.formGroupContent.value.confirmcheck;

当表单被加载并初始化并且我想将表单内容保存在数据库中时,chk 变量的复选框返回值是未定义的,但在任何检查或取消选中后它都会返回真值(0 或 1)。表单初始化后如何获得0值?

标签: angular

解决方案


您需要使用所需的值初始化 FormControl,以编程方式您可以执行以下操作:

this.formGroupContent.get('confirmcheck').setValue(false)

或者直接在表单组的初始化中更好:

this.formGroupContent = this.formBuilder.group({
      confirmcheck: new FormControl(false)
})

如果这不适合您,您始终可以将值转换为严格的布尔值:

!!this.formGroupContent.value.confirmcheck

推荐阅读