Skip to content Skip to sidebar Skip to footer

How In Angular Material To Set Values ​of "Y" And "N" For Component Checkbox?

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:

Solution 1:

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>

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>

See stackblitz


Solution 2:

You can bind your form control value to check the checkbox and pass a value on the change event.

Something like this.

<mat-checkbox formControlName="IS_ACTIVE" (change)="checkboxChange('Y')" [checked]="form.controls.IS_ACTIVE.value == 'Y'">Active</mat-checkbox> 
<mat-checkbox formControlName="IS_ACTIVE" (change)="checkboxChange('N')" [checked]="form.controls.IS_ACTIVE.value == 'N'">Inactive</mat-checkbox> 

I'm not sure if there's a better way to do this. This is just a suggestion. I hope this helps.

EDIT: Well I guess the only option you have is to use [(ngModel)] or formControlName and do a bit of manipulation on your data.

First, when you create your form controls.

this.form = new FormGroup({
    NAME: new FormControl(null, [Validators.required]),
    IS_ACTIVE: new FormControl('Y')// change this to true or false. maybe a condition checking the value for the string. Eg. value == 'Y' ? true : false.
  }

Next, if you are doing this inside a form (which is what I'm assuming) you should use formControlName.

<mat-checkbox formControlName="IS_ACTIVE" formControlName="IS_ACTIVE">Active</mat-checkbox> 

You don't have to check for the change event as the boolean values bind on the form control.

Then before saving on, maniputale the form control's values to 'Y' or 'N'

let boolVal = this.form.controls.IS_ACTIVE.value ? 'Y' : 'N'
//do something with boolVal

This is the only option I can think of to achieve your goal. I hope this helps again.


Solution 3:

Provide value="checked" it will work!

<mat-checkbox value="form.controls.IS_ACTIVE.value == 'Y'"?checked:''" (click)="changeValue(checked)" color="primary">
   some Label
</mat-checkbox>

Post a Comment for "How In Angular Material To Set Values ​of "Y" And "N" For Component Checkbox?"