如何在 Angular Material 中设置“Y"的值?和“N"对于组件复选框? [英] How in Angular Material to set values ​of "Y" and "N" for component checkbox?

查看:16
本文介绍了如何在 Angular Material 中设置“Y"的值?和“N"对于组件复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的数据库不使用布尔值 true 和 false.Angular Material中如何为checkbox设置YN的值?

The database I use does not use boolean values true and false. How in Angular Material to set values ​​of Y and N for component checkbox?

html:

<mat-checkbox formControlName="IS_ACTIVE"  (change)="checkboxChange($event.checked)">
      Active
</mat-checkbox>

ts:

  public setValueOptions = {
    onlySelf: true, 
    emitEvent: false, 
    emitModelToViewChange: false, 
    emitViewToModelChange: false
  }

  initializeForm() {
    if (this.data.action == 'add') {
      this.form = new FormGroup({
        NAME: new FormControl(null, [Validators.required]),
        IS_ACTIVE: new FormControl('Y')
      })
    }
  }

  checkboxChange(checkboxValue) {
    this.form.controls.IS_ACTIVE.setValue(checkboxValue ? 'Y' : 'N', this.setValueOptions);
  }

推荐答案

不要使用 formControlName.如果您有一个带有 [formControlName] 的输入,则 formGroup 存在.因此,您可以在输入中使用 [ngModel] (ngModelChange)

NOT use formControlName. The formGroup exist if you has an input with [formControlName] or not. So, you can use a [ngModel] (ngModelChange) in a input

<mat-checkbox [ngModel]="form.get('IS_ACTIVE').value=='Y'? true:false"
              (ngModelChange)="form.get('IS_ACTIVE').setValue($event? 'Y':'N')"
              [ngModelOptions]="{standalone:true}">
      Active
</mat-checkbox>

更新真的没必要使用[ngModel],只是

Updated Really it's not necesary use [ngModel], just

<mat-checkbox [checked]="form.get('IS_ACTIVE').value=='Y'? true:false"
              (change)="form.get('IS_ACTIVE').setValue($event.checked? 'Y':'N')"
              >
      Active
</mat-checkbox>

参见 stackblitz

这篇关于如何在 Angular Material 中设置“Y"的值?和“N"对于组件复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆