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">
AngularJS ng-checked Directive The ng-checked directive sets the checked attribute of a checkbox or a radiobutton. The checkbox, or radiobutton, will be checked if the expression inside the ng-checked attribute returns true.
FormControlName is used to sync a FormControl in an existing FormGroup to a form control element by name.
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;
DEMO
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With