问题
How can we initialize and manipulate a check box value? I've looked at quite a number of examples, but haven't been able to get any to work.
I'm trying to present a N x M
table where the rows represent tasks, and the columns students. The idea is that checking one of the check-boxes in the table assigns a task to a student.
There is a typescript hash map which contains the value of all the checkboxes
;
assigned : { [key:string]:boolean; } = {};
the hash key is:
var key = a.TaskId + '_' + a.StudentId;
The table is generated with a nested ngFor:
<tr *ngFor="let t of tasks">
<td>Task Name for task... {{t.taskId}} </td>
<td *ngFor="let s of students">
<input type="checkbox" name=#{{t.TaskId}}_{{s.StudentId}} change="onAssignmentChange(t,s)" [checked]="cbValue(t, s)">
</td>
</tr>
the cbValue(t, s)
is below:
cbValue(taskItem, studentItem) {
var key = taskItem.TaskId + '_' +studentItem.StudentId;
return this.assigned[key];
}
This doesn't work, all the checkboxes in the table come up unchecked, no matter what the values in the hash.
I've also tried:
<input type="checkbox" change="onAssignmentChange(t,s)" [checked]="cbValue(t, s)">
<input type="checkbox" change="onAssignmentChange(t,s)" [(ngModel)]={{t.TaskId}}+'_'+{{s.StudentId}} >
<input type="checkbox" change="onAssignmentChange(t,s)" [(ngModel)]="assigned[t.TaskId"+'_'+"s.StudentId"]>
none of which works.
I seem to be quite in the dark here; onAssignmentChange
doesn't get triggered either, there are no Errors in console.
Also,
... name=#{{t.TaskId}}_{{s.StudentId}} ...
is this supposed to be a local target or something?
thanks in advance
回答1:
This is fairly trivial as we're just going to bind straight to the assigned
object, since we're using JavaScript's bracket property accessor we also get a free dynamic instantiation of the property through the template (dirty, maybe, but powerful). Additionally, wherever you're processing this later assume that a missing value is false:
template
<tr *ngFor="let t of tasks">
<td>Task Name for task... {{t.taskName}} </td>
<td *ngFor="let s of students">
<input type="checkbox" name="{{t.taskId}}_{{s.studentId}}" [(ngModel)]="assigned[t.taskId + '_' + s.studentId]">
</td>
</tr>
Here's a plunker to demonstrate: http://plnkr.co/edit/9RorhJnv42cCJanWb80L?p=preview
来源:https://stackoverflow.com/questions/40950285/how-to-initialize-checkbox-from-hashmap-angular-2