简体   繁体   中英

Angular 2 dynamic form with checkbox doesn't work?

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.

I have to make two changes on checkbox control to update the value:

  1. Add [(ngModel)]
  2. update the value on (change) event.

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

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.)

input - Event reference | MDN

@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)">

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM