Zerok
Zerok

Reputation: 1503

Dynamically created input of type checkbox doesn't properly bind value through NgModel

I've got a dynamically created form, wrapped in a table, that appears when I click in an "edit" button of that same row. There are a lot of conditionals inside that dynamic table that when the row is being edited, they show some inputs.

The type, and the binding of those inputs, are all dynamic. Let's check this one:

<td  *ngIf="table?.getInputType(column.key) && table?.isInputActive(column.key, rowIndex) && column.key != table?.buttonsColumn">
    <input *ngIf="table?.getInputType(column.key) != 'select' && column.key != table?.buttonsColumn"
        [type]="table?.getInputType(column.key)"
        [(ngModel)]="sortedValue.referenceObject[column.key]">

This binding works perfect for both selects (which are not included in this snippet), and text fields. But it doesn't bind correctly for checkbox inputs. It doesn't really get the actual value inside the given object, therefore the checkbox is always as "false" (though the value is at "true" sometimes). Consequently, ticking the box and saving the result won't generate any change.

The reference you can see inside the NgModel is perfectly done; I already checked it and the names involved in this key-value object are correctly put. The problem is somewhere else, but I don't know where.

Any help?

Upvotes: 0

Views: 247

Answers (2)

Martin Parenteau
Martin Parenteau

Reputation: 73741

This case is discussed in the issue 7329 on GitHub, and is considered "a limitation of the framework" (the issue is closed). One workaround mentioned in the discussion is to use conditional directives. See this stackblitz for a demo.

<ng-container [ngSwitch]="inputType">
  <input *ngSwitchCase="'checkbox'" type="checkbox" [(ngModel)]="value">
  <input *ngSwitchCase="'password'" type="password" [(ngModel)]="value">
  <input *ngSwitchCase="'email'" type="email" [(ngModel)]="value">
  <input *ngSwitchDefault type="text" [(ngModel)]="value">
</ng-container>

or

<input *ngIf="inputType === 'checkbox'" type="checkbox" [(ngModel)]="value">
<input *ngIf="inputType !== 'checkbox'" type="text" [(ngModel)]="value">

Upvotes: 2

monica
monica

Reputation: 1484

You can try giving an 'id' to each checkbox. I have used rowIndexas id in the below example. You can use it or give some other unique value as id.

<td  *ngIf="table?.getInputType(column.key) && table?.isInputActive(column.key, rowIndex) && column.key != table?.buttonsColumn">
   <input *ngIf="table?.getInputType(column.key) != 'select' && column.key != table?.buttonsColumn" 
                     [id]="rowIndex" [type]="table?.getInputType(column.key)"
                            [(ngModel)]="sortedValue.referenceObject[column.key]">

Upvotes: 0

Related Questions