0

Need help trying to change the value of my Checkbox (mat-checkbox) Angular Material to a value such as 'T' and 'F' that can be passed when my form is submitted with my json object. This 'T' or 'F' from the JSON object is flipping a char flag on my backend. Any help would be appreciated, not sure why I can't seem to figure it out.

-----HTML------------

<div class="form-check">
  <label class="form-check-label" style="padding-right: 10px;">Send to MIP</label>
  <mat-checkbox name="mip" [ngModel]="mip"  class="form-check-input" #mip="ngModel"></mat-checkbox>
</div>

------current value----

{ "mip": true } 

2 Answers 2

1

You aren't binding checkbox UI changes to your model. [ngModel] just binds the model changes to the UI/view. Use [(ngModel)] for two-way binding or add (ngModelChange) for view-to-model binding. To have it handle "T" and "F", implement a getter and setter:

<mat-checkbox [(ngModel)]="mip">Check me!</mat-checkbox>

get mip():boolean {
  return this._mip === "T";
}
set mip(value: boolean) {
  if(value) {
    this._mip = "T";
  } else {
    this._mip = "F";
  }
}
_mip: string = "T";

Or

<mat-checkbox #cb [ngModel]="getMip()" (ngModelChange)="setMip(cb.checked)">Check me!</mat-checkbox>

getMip():boolean {
  return this._mip === "T";
}
setMip(value: boolean) {
  if(value) {
    this._mip = "T";
  } else {
    this._mip = "F";
  }
}
_mip: string = "T"
Sign up to request clarification or add additional context in comments.

Comments

0

You can only have a boolean value for a checkbox, what you can do as a workaround is when you submit the form and in the method where you listen for form submission, you can use ternary operator to assign 'T' or 'F'. example if you have the formData as :

formData = {
    "mip" : true
}

then use :

(formData['mip']===true) ? formData['mip'] = 'T' : formData['mip] = 'F'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.