For a simple checkbox with a string value bound to a FormControl:
export class CheckboxComponent {
formControl: FormControl;
option: {value: string};
constructor() {
this.formControl = new FormControl();
this.option = {value: "MyValue"};
this.formControl.valueChanges.subscribe(console.log);
}
}
<input type="checkbox" [formControl]="formControl" [value]="option.value" name="SomeName" />
The output of the subscribe is true, false, true, false.... I want the angular 2 to bind the string value "MyValue" in the FormControl.
By default angular 2, FormControl and checkboxes seem to bind boolean values which is strange since default browser submit behaviour is to send the value of the checkbox and, in the case of multiple checkboxes with the same name, an array of checkbox values bound to the name of the checkboxes.
Would be pretty useless to submit:
Items=[true, false, true, true, true, false]
Instead of:
Items=[Toothbrush, Floss, Glock, Clean underwear]
So in essence: How to make angular 2 bind the string value not the boolean value?
Kind regards,
I believe I solved your (and my) issue by utilizing a custom directive that "overrides" the default CheckboxControlValueAccessor. Angular2 core sets the onChange event to fire whether the box is checked or not. The code below fires an object with the whether it's checked and the value. You will just need to set the html element as an input of type checkbox, and attached the value you want to track with [value]={valueToTrack}