j.k
j.k

Reputation: 463

Angular 2 Reactive Forms Checkbox - Bind Bool to Number

I have a form model with some indicators that are represented as checkboxes. Currently they model their value as true/false in the form object json. What I would like is for their value to convert from a boolean to a number, 1/0 respectively. Is there a smart way to do this?

Example code:

@Component

template: `
     <form [formGroup]="myForm" (ngSubmit)="save(myForm.value)">
         <input type="checkbox" id="myToggle" formControlName="myToggle"/>
     </form>
`
export class MyComponent implementes OnInit{
private myForm:FormGroup;
myToggle: number;

constructor(private _fb:FormBuilder) {}

ngOnInit() {
    this.myForm = this._fb.group({
      myToggle: [0]
    });
}

Hopefully the above is demonstrating that I'm trying to set the type of "myToggle" to a number. Initializing the form is setting the default to 0 and correctly leaving the checkbox unchecked. However, updating the checkbox to checked will set the form value to true instead of 1. I want it to be updated to 1. Via this question I see that there are some options for converting booleans to numbers. However, I'm unsure of exactly how to implement this with the reactive form model.

Upvotes: 2

Views: 6037

Answers (1)

mat3e
mat3e

Reputation: 791

FormControl has registerOnChange method, which allows you to specify a callback executed after every change.

Having your example you can access control let ctrl = this.myForm.controls["myToggle"] (I'd prefer create this manually) and then you can do sth like ctrl.registerOnChange(() => ctrl.patchValue(ctrl.value ? 1 : 0));.

Upvotes: 1

Related Questions