7

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">
2

2 Answers 2

14

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

Sign up to request clarification or add additional context in comments.

6 Comments

Just wanted to add here that I could only get your solution to work for one checkbox. With multiple dynamic checkboxes I had to write a function and sent the event and prop out to it.
Hi, can you answer my question stackoverflow.com/questions/47889068/…
could be helpful, if you can answer this.
In your example, what is "myForm"? I don't see it declared.
@AppDreamer Well, OP didn't specify the name of the 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 :)
|
8

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

1 Comment

may be you can answer my question, stackoverflow.com/questions/65429846/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.