Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a checkbox value to Angular form control name?

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">
like image 403
Karty Avatar asked Nov 09 '17 08:11

Karty


People also ask

How do you checked the checkbox in Angular?

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.

What is form control name in Angular?

FormControlName is used to sync a FormControl in an existing FormGroup to a form control element by name.


2 Answers

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

like image 166
AT82 Avatar answered Nov 06 '22 16:11

AT82


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

like image 34
Erik Grosskurth Avatar answered Nov 06 '22 17:11

Erik Grosskurth