I want to assign the check box's value instead of true or false. How can i achieve this?
<input formControlName="ota" value="OTA" type="checkbox">
I want to assign the check box's value instead of true or false. How can i achieve this?
<input formControlName="ota" value="OTA" type="checkbox">
You can use a change event to then use patchValue (or setValue) to assign the $event.target.value if it's checked. If not, then assign something else. Here I assign an empty string:
<input formControlName="ota" (change)="$event.target.checked ?
otaCtrl.patchValue($event.target.value) : otaCtrl.patchValue('')"
value="OTA" type="checkbox">
where otaCtrl is a variable for your form control:
otaCtrl: FormControl;
// code...
this.otaCtrl = this.myForm.get('ota') as FormControl;
FormGroup, so I used a pseudo name for the formgroup name, i.e myGroup. There is a demo attached to my answer, so you can also check that out :)I couldn't get the accepted answer to work with multiple dynamic built form checkbox elements. So based on that selected answer I did this (assuming the value for a checkbox was a boolean) :
export class DynamicFormComponent implements OnInit {
activeCtrl: FormControl;
...
updateCheckBoxVal(prop, eve) {
this.activeCtrl = this.form.get(prop.key) as FormControl;
this.activeCtrl.patchValue(eve.checked);
}
}
The HTML file:
<label *ngSwitchCase="'checkbox'" [attr.for]="prop"> {{prop.label}}
<input
[formControlName]="prop.key"
[id]="prop.key"
[type]="prop.type"
[checked]="prop.value"
(change)="updateCheckBoxVal(prop, $event.target);"
/>
</label>
Hope this helps someone, and thanks to @AJT_82 for the inspiration