Reputation: 6373
Angular 2 dynamic form example from Angular 2 website is modified slightly to include checkbox control into the mix. Here is the plnkr with checkbox added.
Unable to get the checkbox checked value on form submit. Textbox and dropdown values are updated on submit though.
Note: I have also tried putting [(ngModel)]
on checkbox but value doesn't update even then.
Upvotes: 1
Views: 6090
Reputation: 110
@Nexus23's solution works but the usage of template reference var #ck
allows for only one checkbox within a FormGroup.
You can set a FormControl's value (in a FormGroup) directly from the change event:
(change)="formGroup.controls[element.name].setValue($event.target.checked)"
Since FormControl.setValue's emitEvent, emitModelToViewChange and emitViewToModelChange default to true
, it's seems not necessary to update other attributes manually.
Modified for angular's dynamic form (working example on stackblitz):
<input *ngSwitchCase="'checkbox'" [formControlName]="question.key"
[id]="question.key" [type]="question.type" (change)="form.controls[question.key].setValue($event.target.checked)">
Upvotes: 1
Reputation: 1
I think that since this is used for dynamic forms, we can't hard-code the checkbox reference ID as we might have more than one checkbox in the form. Also, if the initial value is checked, the checkbox still appears unchecked. The code below fixes these issues (tested with Angular 2 rc4). I've also added a label for the checkbox. Hope that helps.
<label *ngSwitchCase="'checkbox'"><input (change)="question.value = $event.target.checked" [(ngModel)]="question.value" [attr.checked]="question.value ? true : null" [formControlName]="question.key" [id]="question.key" [type]="question.type"> {{question.label}}</label>
Upvotes: 0
Reputation: 6373
I have to make two changes on checkbox control to update the value:
Here is the plnkr with fix if anyone encounters the same issue.
For brevity here is what checkbox control looks like now:
<input #ck *ngSwitchWhen="'checkbox'" (change)="control.value = ck.checked" [id]="control.key" [ngControl]="control.key" [type]="control.type" [class.error]="!control.valid"
[(ngModel)]="control.value" class="form-control">
Upvotes: 2
Reputation: 11
I think the problem is linked to input behaviour described by MDN:
The DOM input event is fired synchronously when the value of an <input> or <textarea> element is changed. (For input elements with type=checkbox or type=radio, the input event does not fire when a user clicks the control, because the value attribute does not change.)
Upvotes: 1